package com.dk.mdm.service.report;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dk.common.model.pojo.PageList;
import com.dk.common.response.ResponseCodeEnum;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.common.util.ExcelUtils;
import com.dk.common.util.ExportMoreView;
import com.dk.common.util.ExportView;
import com.dk.common.util.RedisUtil;
import com.dk.mdm.mapper.ivt.InboundItemMapper;
import com.dk.mdm.mapper.ivt.OutboundItemMapper;
import com.dk.mdm.mapper.report.ReportMapper;
import com.dk.mdm.model.report.ExcelDataHandler;
import com.dk.mdm.model.report.ExcelExportStyleImpl;
import com.dk.mdm.model.report.ExcelIndex;
import com.dk.mdm.model.report.analysis.BudgetQuotationStaff;
import com.dk.mdm.model.report.analysis.PotentialCustomerAnalysis;
import com.dk.mdm.model.report.analysis.PotentialCustomerAnalysisStaff;
import com.dk.mdm.model.report.department.DepartmentCollectionRanking;
import com.dk.mdm.model.report.department.DepartmentTransactionRanking;
import com.dk.mdm.model.report.from.PotentialCustomerAnalysisFrom;
import com.dk.mdm.model.report.from.Transaction;
import com.dk.mdm.model.report.product.ProductDistribution;
import com.dk.mdm.model.report.received.ArrearsInfo;
import com.dk.mdm.model.report.received.ArrearsInfoStaff;
import com.dk.mdm.model.report.received.ReceivedTask;
import com.dk.mdm.model.report.received.ReceivedTaskStaff;
import com.dk.mdm.model.report.sale.*;
import com.dk.mdm.model.report.staff.StaffCollectionRanking;
import com.dk.mdm.model.report.staff.StaffTransactionRanking;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author : 常皓宁
 * @desc : 报表数据源
 * @date : 2024/4/11 8:49
 */
@Service
@Slf4j
public class ReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private InboundItemMapper inboundItemMapper;

    @Autowired
    private OutboundItemMapper outboundItemMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * @desc : 销售汇总表
     * @author : 王英杰
     * @date : 2024/4/26 16:43
     */
    public ResponseResultVO<Map<String, Object>> getOrderSummary(Map<String, Object> param) {
        if (param.get("querys") != null) {
            JSONObject querys = JSONObject.parseObject(param.get("querys").toString());
            param.put("querys", querys);
        }
        Map<String, Object> m = reportMapper.getOrderSummary(param);
        JSONObject jObject = JSONObject.parseObject(m.get("f_get_order_summary").toString());
        return ResponseResultUtil.success(jObject);
    }

    /**
     * @desc : 销售汇总表明细
     * @author : 付斌
     * @date : 2024/4/26 16:43
     */
    public ResponseResultVO<Map<String, Object>> getOrderSummaryItem(Map<String, Object> param) {
        if (param.get("querys") != null) {
            JSONObject querys = JSONObject.parseObject(param.get("querys").toString());
            param.put("querys", querys);
        }
        Map<String, Object> m = reportMapper.getOrderSummaryItem(param);
        JSONObject jObject = JSONObject.parseObject(m.get("f_get_order_summary_item").toString());
        return ResponseResultUtil.success(jObject);
    }

    /**
     * @desc : 查询库存
     * @author : 常皓宁
     * @date : 2024/4/11 8:52
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getIvtDetailReport(Map<String, Object> param) {
        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }
        // 获取系统基础数据
        PageList data = new PageList<>();
        param.put("start", (Integer.parseInt(param.get("currentPage").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()));
        param.put("end", Integer.parseInt(param.get("pageSize").toString()));
        List<Map<String, Object>> dataList = new ArrayList<>();
        if (param.get("flgViewItem") == null) {
            // 查询主表
            dataList = reportMapper.getIvtDetailReport(param);
        } else {
            // 查询明细
            dataList = reportMapper.getIvtDetailBatchReport(param);
        }
        data.setList(dataList);
        if (param.get("flgViewItem") == null) {
            // 查询主表
            data.setTotal(reportMapper.getIvtDetailReportCount(param));
        } else {
            // 查询明细
            data.setTotal(reportMapper.getIvtDetailBatchReportCount(param));
        }
//        List<Map<String, Object>> list = reportMapper.getIvtDetailReport(param);
//        data.setList(list);
//        data.setTotal(reportMapper.getIvtDetailReportCount(param));
        data.setPageSize((Integer) param.get("pageSize"));
        data.setCurrentPage((Integer) param.get("currentPage"));
        return ResponseResultUtil.success(data);
    }

    /**
     * @desc : 采购明细报表（明细）
     * @author : 宋扬
     * @date : 2024/4/10 16:39
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getPurDetailReport(Map<String, Object> param) {
        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }
        // 获取系统基础数据
        List<Map<String, Object>> list = new ArrayList<>();
        PageList data = new PageList<>();
        param.put("start", (Integer.parseInt(param.get("currentPage").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()));
        param.put("end", Integer.parseInt(param.get("pageSize").toString()));
        List<Map<String, Object>> dataList = new ArrayList<>();
        if (param.get("flgViewItem") == null) {
            // 查询主表
            dataList = reportMapper.getPurReport(param);
        } else {
            // 查询明细
            dataList = reportMapper.getPurDetailReport(param);
        }
        data.setList(dataList);
        if (param.get("flgViewItem") == null) {
            // 查询主表
            data.setTotal(reportMapper.getPurReportCount(param));
        } else {
            // 查询明细
            data.setTotal(reportMapper.getPurDetailReportCount(param));
        }

        data.setPageSize((Integer) param.get("pageSize"));
        data.setCurrentPage((Integer) param.get("currentPage"));
        return ResponseResultUtil.success(data);
    }

    /**
     * @desc : 销售明细报表
     * @author : 宋扬
     * @date : 2024/4/11 13:22
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getOrderDetailReport(Map<String, Object> param) {
        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }
        // 获取系统基础数据
        List<Map<String, Object>> list = new ArrayList<>();
        PageList data = new PageList<>();
        param.put("start", (Integer.parseInt(param.get("currentPage").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()));
        param.put("end", Integer.parseInt(param.get("pageSize").toString()));
        List<Map<String, Object>> dataList = new ArrayList<>();
        if (param.get("flgViewItem") == null) {
            // 查询主表
            dataList = reportMapper.getOrderReport(param);
        } else {
            // 查询明细
            dataList = reportMapper.getOrderDetailReport(param);
        }
        data.setList(dataList);
        if (param.get("flgViewItem") == null) {
            // 查询主表
            data.setTotal(reportMapper.getOrderReportCount(param));
        } else {
            // 查询明细
            data.setTotal(reportMapper.getOrderDetailReportCount(param));
        }

        data.setPageSize((Integer) param.get("pageSize"));
        data.setCurrentPage((Integer) param.get("currentPage"));
        return ResponseResultUtil.success(data);
    }

    /**
     * @desc : 出库明细报表
     * @author : 宋扬
     * @date : 2024/4/11 16:54
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getOutboundDetailReport(Map<String, Object> param) {
        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }
        // 获取系统基础数据
        PageList data = new PageList<>();
        param.put("start", (Integer.parseInt(param.get("currentPage").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()));
        param.put("end", Integer.parseInt(param.get("pageSize").toString()));
        List<Map<String, Object>> dataList = new ArrayList<>();
        if (param.get("flgViewItem") == null) {
            // 查询主表
            dataList = reportMapper.getOutboundReport(param);
        } else {
            // 查询明细
            dataList = reportMapper.getOutboundDetailReport(param);
        }
        data.setList(dataList);
        if (param.get("flgViewItem") == null) {
            // 查询主表
            data.setTotal(reportMapper.getOutboundReportCount(param));
        } else {
            // 查询明细
            data.setTotal(reportMapper.getOutboundDetailReportCount(param));
        }
        data.setPageSize((Integer) param.get("pageSize"));
        data.setCurrentPage((Integer) param.get("currentPage"));
        return ResponseResultUtil.success(data);
    }

    /**
     * @desc : 入库明细报表
     * @author : 宋扬
     * @date : 2024/4/11 16:54
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getInboundDetailReport(Map<String, Object> param) {
        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }
        // 获取系统基础数据
        PageList data = new PageList<>();
        param.put("start", (Integer.parseInt(param.get("currentPage").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()));
        param.put("end", Integer.parseInt(param.get("pageSize").toString()));
        List<Map<String, Object>> dataList = new ArrayList<>();
        if (param.get("flgViewItem") == null) {
            // 查询主表
            dataList = reportMapper.getInboundlReport(param);
        } else {
            // 查询明细
            dataList = reportMapper.getInboundDetailReport(param);
        }
        data.setList(dataList);
        if (param.get("flgViewItem") == null) {
            // 查询主表
            data.setTotal(reportMapper.getInboundlReportCount(param));
        } else {
            // 查询明细
            data.setTotal(reportMapper.getInboundDetailReportCount(param));
        }
        data.setPageSize((Integer) param.get("pageSize"));
        data.setCurrentPage((Integer) param.get("currentPage"));
        return ResponseResultUtil.success(data);
    }

    /**
     * @desc : 客户收款明细表
     * @author : 宋扬
     * @date : 2024/4/16 11:29
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getRecPayDetailReport(Map<String, Object> param) {
        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }
        // 获取系统基础数据
        PageList data = new PageList<>();
        param.put("start", (Integer.parseInt(param.get("currentPage").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()));
        param.put("end", Integer.parseInt(param.get("pageSize").toString()));
        // 查询主表
        List<Map<String, Object>> dataList = reportMapper.getRecPayDetailReport(param);
        data.setList(dataList);
        data.setTotal(reportMapper.getRecPayDetailReportCount(param));
        data.setPageSize((Integer) param.get("pageSize"));
        data.setCurrentPage((Integer) param.get("currentPage"));
        return ResponseResultUtil.success(data);
    }


    /**
     * @desc : 销售跟踪表 列表查询
     * @author : 于继渤
     * @date : 2024/4/16 11:27
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getSalesTrackingReport(Map<String, Object> param) {

        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }
        // 定义返回值
        PageList data = new PageList<>();
        // 获取SKU商品
        param.put("start", (Integer.parseInt(param.get("currentPage").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()));
        param.put("end", Integer.parseInt(param.get("pageSize").toString()));
        List<Map<String, Object>> dataList = reportMapper.getSalesTrackingReport(param);
        data.setList(dataList);
        data.setTotal(reportMapper.getSalesTrackingReportCount(param));
        data.setPageSize((Integer) param.get("pageSize"));
        data.setCurrentPage((Integer) param.get("currentPage"));
        return ResponseResultUtil.success(data);
    }


    /**
     * @desc : 销售明细
     * @author : 于继渤
     * @date : 2024/4/16 11:27
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getSalesItemReport(Map<String, Object> param) {

        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }
        // 定义返回值
        PageList data = new PageList<>();
        // 获取SKU商品
        param.put("start", (Integer.parseInt(param.get("currentPage").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()));
        param.put("end", Integer.parseInt(param.get("pageSize").toString()));
        List<Map<String, Object>> dataList = reportMapper.getSalesItemReport(param);
        data.setList(dataList);
        data.setTotal(reportMapper.getSalesItemReportCount(param));
        data.setPageSize((Integer) param.get("pageSize"));
        data.setCurrentPage((Integer) param.get("currentPage"));
        return ResponseResultUtil.success(data);
    }


    /**
     * @desc : 采购跟踪表 列表查询
     * @author : 王英杰
     * @date : 2024/4/16 11:27
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getPurTrackingReport(Map<String, Object> param) {

        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }
        // 定义返回值
        PageList data = new PageList<>();
        // 获取SKU商品
        param.put("start", (Integer.parseInt(param.get("currentPage").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()));
        param.put("end", Integer.parseInt(param.get("pageSize").toString()));
        List<Map<String, Object>> dataList = reportMapper.getPurTrackingReport(param);
        data.setList(dataList);
        data.setTotal(reportMapper.getPurTrackingReportCount(param));
        data.setPageSize((Integer) param.get("pageSize"));
        data.setCurrentPage((Integer) param.get("currentPage"));
        return ResponseResultUtil.success(data);
    }


    /**
     * @desc : 采购跟踪表 明细查询
     * @author : 王英杰
     * @date : 2024/4/16 11:27
     */
    public ResponseResultVO getPurTrackingReportDetail(String purId) {

        return ResponseResultUtil.success(reportMapper.getPurTrackingReportDetail(purId));
    }

    /**
     * @desc : 销售跟踪表 明细查询
     * @author : 于继渤
     * @date : 2024/4/16 11:27
     */
    public ResponseResultVO getSalesTrackingReportDetail(String id) {
        return ResponseResultUtil.success(reportMapper.getSalesTrackingReportDetail(id));
    }


    /**
     * @desc : 日结对账表
     * @date : 2024/4/24 15:11
     * @author : 寇珊珊
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getDailyReconciliationReport(Map<String, Object> param) {
        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }
        // 定义返回值
        PageList data = new PageList<>();
        param.put("start", (Integer.parseInt(param.get("currentPage").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()));
        param.put("end", Integer.parseInt(param.get("pageSize").toString()));
        List<Map<String, Object>> dataList = reportMapper.getDailyReconciliationReport(param);
        data.setList(dataList);
        data.setTotal(reportMapper.getDailyReconciliationReportCount(param));
        data.setPageSize((Integer) param.get("pageSize"));
        data.setCurrentPage((Integer) param.get("currentPage"));
        return ResponseResultUtil.success(data);
    }

    /**
     * @desc :  日结对账表-查销售订单
     * @date : 2024/4/24 15:11
     * @author : 寇珊珊
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getDailyReconciliationReportByOrder(Map<String, Object> param) {
        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }
        // 定义返回值
        PageList data = new PageList<>();
        param.put("start", (Integer.parseInt(param.get("currentPage").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()));
        param.put("end", Integer.parseInt(param.get("pageSize").toString()));
        List<Map<String, Object>> dataList = reportMapper.getDailyReconciliationReportByOrder(param);
        data.setList(dataList);
        data.setTotal(reportMapper.getDailyReconciliationReportByOrderCount(param));
        data.setPageSize((Integer) param.get("pageSize"));
        data.setCurrentPage((Integer) param.get("currentPage"));
        return ResponseResultUtil.success(data);
    }


    /**
     * @desc :  日结对账表-查销售出库
     * @date : 2024/4/24 15:11
     * @author : 寇珊珊
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getDailyReconciliationReportByOut(Map<String, Object> param) {
        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }
        // 定义返回值
        PageList data = new PageList<>();
        param.put("start", (Integer.parseInt(param.get("currentPage").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()));
        param.put("end", Integer.parseInt(param.get("pageSize").toString()));
        List<Map<String, Object>> dataList = reportMapper.getDailyReconciliationReportByOut(param);
        data.setList(dataList);
        data.setTotal(reportMapper.getDailyReconciliationReportByOutCount(param));
        data.setPageSize((Integer) param.get("pageSize"));
        data.setCurrentPage((Integer) param.get("currentPage"));
        return ResponseResultUtil.success(data);
    }


    /**
     * @desc :  日结对账表-查收款单
     * @date : 2024/4/24 15:11
     * @author : 寇珊珊
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getDailyReconciliationReportByPay(Map<String, Object> param) {
        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }
        // 定义返回值
        PageList data = new PageList<>();
        param.put("start", (Integer.parseInt(param.get("currentPage").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()));
        param.put("end", Integer.parseInt(param.get("pageSize").toString()));
        List<Map<String, Object>> dataList = reportMapper.getDailyReconciliationReportByPay(param);
        data.setList(dataList);
        data.setTotal(reportMapper.getDailyReconciliationReportByPayCount(param));
        data.setPageSize((Integer) param.get("pageSize"));
        data.setCurrentPage((Integer) param.get("currentPage"));
        return ResponseResultUtil.success(data);
    }

    /**
     * @desc : 收发存汇总报表
     * @author : 宋扬
     * @date : 2024/4/20 13:30
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getIvtSumReport(Map<String, Object> param) {
        if (param.get("querys") != null) {
            JSONObject querys = JSONObject.parseObject(param.get("querys").toString());
            param.put("querys", querys);
        }

        List<Map<String, Object>> list = reportMapper.getIvtSumReport(param);
        JSONObject jObject = JSONObject.parseObject(list.get(0).get("f_query_ivt_rds").toString());
        List dataList = jObject.get("data") != null ? JSONObject.parseArray(jObject.get("data").toString())
                .toJavaList(Map.class) : new ArrayList();
        if (!dataList.isEmpty()) {
            List<Map<String,Object>> newDataList = new ArrayList<>();
            newDataList.addAll(dataList);
            if (Boolean.parseBoolean(String.valueOf(param.get("openingNumberZero")))) {
                newDataList = newDataList.stream().filter((Map data) -> Double.valueOf(String.valueOf( data.get("openingIvtQty"))) != 0).collect(Collectors.toList());
            }
            if (Boolean.parseBoolean(String.valueOf(param.get("currentNumberZero")))) {
                newDataList = newDataList.stream().filter((Map data) -> Double.valueOf(String.valueOf(data.get("currentIntoQty"))) != 0).collect(Collectors.toList());
            }
            if (Boolean.parseBoolean(String.valueOf(param.get("currentOutNumberZero")))) {
                newDataList = newDataList.stream().filter((Map data) -> Double.valueOf(String.valueOf(data.get("currentOutQty"))) != 0).collect(Collectors.toList());
            }
            if (Boolean.parseBoolean(String.valueOf(param.get("endingIvtNumberZero")))) {
                newDataList = newDataList.stream().filter((Map data) -> Double.valueOf(String.valueOf(data.get("endingIvtQty"))) != 0).collect(Collectors.toList());
            }
            dataList.clear();
            dataList.addAll(newDataList);
        }

        // 定义返回值
        PageList data = new PageList<>();
        data.setPageSize((int) param.get("pageSize")).setCurrentPage((int) param.get("currentPage"))
                .setTotal(Long.parseLong(jObject.get("pageTotal").toString()))
                .setList(dataList);

        if ("查询成功".equals(jObject.get("message").toString())) {
            return ResponseResultUtil.success(data);
        } else {
            return ResponseResultUtil.error(666, jObject.get("message").toString());
        }
    }

    /**
     * @desc : 收发存汇总报表-明细
     * @author : 宋扬
     * @date : 2024/4/23 14:10
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getIvtItemReport(Map<String, Object> param) {
        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }

        List<Map<String, Object>> list = reportMapper.getIvtItemReport(param);
        JSONObject jObject = JSONObject.parseObject(list.get(0).get("f_query_ivt_rds_item").toString());
        List dataList = jObject.get("data") != null ? JSONObject.parseArray(jObject.get("data").toString())
                .toJavaList(Map.class) : new ArrayList();

        // 定义返回值
        PageList data = new PageList<>();
        data.setPageSize((int) param.get("pageSize")).setCurrentPage((int) param.get("currentPage"))
                .setTotal(Long.parseLong(jObject.get("pageTotal").toString()))
                .setList(dataList);

        if ("查询成功".equals(jObject.get("message").toString())) {
            return ResponseResultUtil.success(data);
        } else {
            return ResponseResultUtil.error(666, jObject.get("message").toString());
        }
    }

    /**
     * @desc : 供应商往来余额表
     * @author : 常皓宁
     * @date : 2024/4/25 13:27
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getSupAccount(Map<String, Object> param) {
        param.put("start", (Integer.parseInt(param.get("currentPage").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()));
        param.put("end", Integer.parseInt(param.get("pageSize").toString()));
        // 获取系统基础数据
        List<Map<String, Object>> list = reportMapper.getSupAccount(param);
        PageList data = new PageList<>();
        data.setList(list);
        return ResponseResultUtil.success(data);
    }

    /**
     * @desc : 供应商往来余额表明细
     * @author : 常皓宁
     * @date : 2024/4/25 13:27
     */
    public ResponseResultVO<List<Map<String, Object>>> getSupAccountItem(Map<String, Object> param) {
        // 获取系统基础数据
        List<Map<String, Object>> list = reportMapper.getSupAccountItem(param);
        return ResponseResultUtil.success(list);
    }

    /**
     * @desc : 资金日记账
     * @author : 常皓宁
     * @date : 2024/4/26 16:43
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getFundReport(Map<String, Object> param) {
        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }

        List<Object> objects = new ArrayList<>();
        if (param.get("macIds") instanceof ArrayList<?>) {
            for (Object o : (List<?>) param.get("macIds")) {
                objects.add(String.class.cast(o));
            }
        }
        if (objects.isEmpty()){
            param.remove("macIds");
        }
        // 获取资金日记账
        List<Map<String, Object>> list = reportMapper.getFundReport(param);
        JSONObject jObject = JSONObject.parseObject(list.get(0).get("f_get_fund_report").toString());
        List dataList = jObject.get("data") != null ? JSONObject.parseArray(jObject.get("data").toString())
                .toJavaList(Map.class) : new ArrayList();

        // 定义返回值
        PageList data = new PageList<>();
        data.setPageSize((int) param.get("pageSize")).setCurrentPage((int) param.get("currentPage"))
                .setTotal(Long.parseLong(jObject.get("pageTotal").toString()))
                .setList(dataList);

        if ("查询成功".equals(jObject.get("message").toString())) {
            return ResponseResultUtil.success(data);
        } else {
            return ResponseResultUtil.error(666, jObject.get("message").toString());
        }

    }


    /**
     * @desc : 销售简报
     * @date : 2024/5/6 8:43
     * @author : 寇珊珊
     */
    public ResponseResultVO<Map<String, Object>> getReportBatch(Map<String, Map<String, Object>> param) {
        Map<String, Object> result = new HashMap<>();
        for (String key : param.keySet()) {
            JSONObject valueObj = JSONObject.parseObject(reportMapper.getReportBatch(param.get(key)).get("report").getValue());
            result.put(key, valueObj);
        }
        return ResponseResultUtil.success(result);
    }


    //    @Autowired
//    private LogReportExportFeign logReportExportFeign;
    @Transactional(rollbackFor = {Exception.class})
    public void export(HttpServletResponse response, String uuid) throws Exception {

        ExportMoreView exportMoreView = new ExportMoreView();

        List<ExportView> exportViews = new ArrayList<>();

        Map<String, Object> redisData = ((Map<String, Object>) redisUtil.get(uuid));

        Map<String, Map<String, Object>> params = (Map<String, Map<String, Object>>) redisData.get("params");
        /* 查询条件 */
        String searchCondition = redisData.get("searchCond").toString();
        /* 数据库查询出来的数据 */
        Map<String, Object> reportData = getReportBatch(params).getData();

        String fileName = redisData.get("fileName").toString();
//        String filePath = redisData.get("filePath").toString();

        exportViews.add(new ExportView());
        exportViews.get(0).setCls(ExcelIndex.class);
        ExportParams indexExportParams = new ExportParams(searchCondition, "报表目录");
        indexExportParams.setDataHandler(new ExcelDataHandler());
        exportViews.get(0).setExportParams(indexExportParams);
        exportViews.get(0).setTitleHeight(60);
        List<ExcelIndex> sheetList = new ArrayList<>();
//        String currentUserId = null;
//        Long cpId = null;
        for (String key : params.keySet()) {
            sheetList.add(new ExcelIndex().setSheetName(TITLE_MAP.get(key)));
            Map<String, Object> currentMap = params.get(key);
            /* 手动处理一下 userId */
//            if(currentUserId == null){
//                currentUserId = currentMap.get("userId").toString();
//            }
            /* 手动处理cpId */
//            if(cpId == null){
//                cpId = Long.valueOf(currentMap.get("cpId").toString());
//            }
            Class<?> clazz = CLASS_MAP.get(key);
            List<?> list = JSONArray.parseArray(JSONArray.toJSONString(((Map<String, Object>) reportData.get(key)).get(currentMap.get("items").toString())), clazz);
            ExportParams exportParams = new ExportParams(
                    TITLE_MAP.get(key),
                    getTotal(currentMap.get("secondTitle").toString(), (Map<String, Object>) reportData.get(key), (List<String>) currentMap.get("calc10000")),
                    TITLE_MAP.get(key));

            exportParams.setStyle(ExcelExportStyleImpl.class);

            ExportView exportView = new ExportView(exportParams, list, clazz);
            exportViews.add(exportView);
        }
        exportViews.get(0).setDataList(sheetList);
        exportMoreView.setMoreViewList(exportViews);

        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日HH时mm分ss秒");
        String currentTime = LocalDateTime.now().format(outputFormatter);

        /* 导出成功之前 插入日志表 */
//        LogReportExportVo logReportExportVo = new LogReportExportVo()
//                .setReportName(fileName + "-" +currentTime +".xls")
//                .setReportPath(filePath)
//                .setCpId(cpId)
//                .setQueryItems(JSONObject.parseObject(JSONObject.toJSONString(params)))
//                .setExportData(new JSONObject(reportData))
//                .setOpCreateUserId(currentUserId);
//        ResponseResultVO<?> insertRes = logReportExportFeign.insert(logReportExportVo);
//        if(insertRes.getCode() == 200){
        ExcelUtils.defaultExportMoreSheet(fileName + "-" + currentTime + ".xls", response, exportMoreView);
//        }else{
//            throw new BaseBusinessException(insertRes.getCode(),insertRes.getMessage());
//        }
    }

    /**
     * @desc : 客户往来账
     * @author : 宋扬
     * @date : 2024/5/10 10:32
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getMacRecCurrentReport(Map<String, Object> param) {
        if (param.get("querys") != null) {
            JSONObject querys = JSONObject.parseObject(param.get("querys").toString());
            param.put("querys", querys);
        }

        List<Map<String, Object>> list = reportMapper.getMacRecCurrentReport(param);
        JSONObject jObject = JSONObject.parseObject(list.get(0).get("f_query_mac_rec_current").toString());
        List dataList = jObject.get("data") != null ? JSONObject.parseArray(jObject.get("data").toString())
                .toJavaList(Map.class) : new ArrayList();

        // 定义返回值
        PageList data = new PageList<>();
        data.setPageSize((int) param.get("pageSize")).setCurrentPage((int) param.get("currentPage"))
                .setTotal(Long.parseLong(jObject.get("pageTotal").toString()))
                .setList(dataList);

        if ("查询成功".equals(jObject.get("message").toString())) {
            return ResponseResultUtil.success(data);
        } else {
            return ResponseResultUtil.error(666, jObject.get("message").toString());
        }
    }

    /**
     * @desc : 客户往来账明细
     * @author : 宋扬
     * @date : 2024/5/10 10:32
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getMacRecCurrentItemReport(Map<String, Object> param) {
        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }

        List<Map<String, Object>> list = reportMapper.getMacRecCurrentItemReport(param);
        JSONObject jObject = JSONObject.parseObject(list.get(0).get("f_query_mac_rec_current_item").toString());
        List dataList = jObject.get("data") != null ? JSONObject.parseArray(jObject.get("data").toString())
                .toJavaList(Map.class) : new ArrayList();

        // 定义返回值
        PageList data = new PageList<>();
        data.setPageSize((int) param.get("pageSize")).setCurrentPage((int) param.get("currentPage"))
                .setTotal(Long.parseLong(jObject.get("pageTotal").toString()))
                .setList(dataList);

        if ("查询成功".equals(jObject.get("message").toString())) {
            return ResponseResultUtil.success(data);
        } else {
            return ResponseResultUtil.error(666, jObject.get("message").toString());
        }
    }

    /**
     * @desc : 供应商往来账
     * @author : 宋扬
     * @date : 2024/5/10 10:32
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getMacPayCurrentReport(Map<String, Object> param) {
        if (param.get("querys") != null) {
            JSONObject querys = JSONObject.parseObject(param.get("querys").toString());
            param.put("querys", querys);
        }

        List<Map<String, Object>> list = reportMapper.getMacPayCurrentReport(param);
        JSONObject jObject = JSONObject.parseObject(list.get(0).get("f_query_mac_pay_current").toString());
        List dataList = jObject.get("data") != null ? JSONObject.parseArray(jObject.get("data").toString())
                .toJavaList(Map.class) : new ArrayList();

        // 定义返回值
        PageList data = new PageList<>();
        data.setPageSize((int) param.get("pageSize")).setCurrentPage((int) param.get("currentPage"))
                .setTotal(Long.parseLong(jObject.get("pageTotal").toString()))
                .setList(dataList);

        if ("查询成功".equals(jObject.get("message").toString())) {
            return ResponseResultUtil.success(data);
        } else {
            return ResponseResultUtil.error(666, jObject.get("message").toString());
        }
    }

    /**
     * @desc : 供应商往来账明细
     * @author : 宋扬
     * @date : 2024/5/10 10:32
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getMacPayCurrentItemReport(Map<String, Object> param) {
        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }

        List<Map<String, Object>> list = reportMapper.getMacPayCurrentItemReport(param);
        JSONObject jObject = JSONObject.parseObject(list.get(0).get("f_query_mac_pay_current_item").toString());
        List dataList = jObject.get("data") != null ? JSONObject.parseArray(jObject.get("data").toString())
                .toJavaList(Map.class) : new ArrayList();

        // 定义返回值
        PageList data = new PageList<>();
        data.setPageSize((int) param.get("pageSize")).setCurrentPage((int) param.get("currentPage"))
                .setTotal(Long.parseLong(jObject.get("pageTotal").toString()))
                .setList(dataList);

        if ("查询成功".equals(jObject.get("message").toString())) {
            return ResponseResultUtil.success(data);
        } else {
            return ResponseResultUtil.error(666, jObject.get("message").toString());
        }
    }

    /**
     * @desc : 客户收支表查询
     * @author : 刘尧
     * @date : 2024/6/6 14:27
     */
    public ResponseResultVO<List<Map<String, Object>>> getCusRecPayReportItem(Map<String, Object> params) {
        params.put("start", (Integer.parseInt(params.get("currentPage").toString()) - 1) * Integer.parseInt(params.get("pageSize").toString()));
        params.put("end", Integer.parseInt(params.get("pageSize").toString()));
        List<Map<String, Object>> arrears = reportMapper.getUserArrears(params);
        for (Map<String, Object> map : arrears) {
            params.put("objectId", map.get("objectId"));
            Map<String, Object> orderAmt = reportMapper.getOrderAmt(params);
            Map<String, Object> outBoundAmt = reportMapper.getOutboundAmt(params);
            Map<String, Object> startAmt = reportMapper.getStartAmt(params);
            Map<String, Object> sales = new HashMap<>();
            sales.put("facAmt", Double.valueOf(String.valueOf(orderAmt.get("orderAmt")).equals("null") ? "0" : String.valueOf(orderAmt.get("orderAmt")))
                    + Double.valueOf(String.valueOf(outBoundAmt.get("outboundAmt")).equals("null") ? "0" : String.valueOf(outBoundAmt.get("outboundAmt"))));
            // 获取收支额
            Map<String, Object> incomeExpenditure = reportMapper.getIncomeExpenditure(params);
            map.put("arrears", Double.valueOf(String.valueOf(sales.get("facAmt")).equals("null") ? "0" : String.valueOf(sales.get("facAmt")))
                    - Double.valueOf(String.valueOf(incomeExpenditure.get("arrears")).equals("null") ? "0" : String.valueOf(incomeExpenditure.get("arrears")))
                    + Double.valueOf(String.valueOf(startAmt.get("startAmt")).equals("null") ? "0" : String.valueOf(startAmt.get("startAmt"))));
/*            params.put("objectId", map.get("objectId"));
            List<Map<String, Object>> items = reportMapper.getCusRecPayReportItemByUser(params);
            List<Map<String, Object>> psiOrderByUser = reportMapper.getPsiOrderByUser(params);
            List<Map<String, Object>> outAmtByUser = reportMapper.getOutboundAmtByUser(params);
            items.addAll(outAmtByUser);
            items.addAll(psiOrderByUser);
            // 筛选出符合条件的明细
            List<Map<String, Object>> userArrearsItem = items.stream()
                    .filter(item -> item.get("objectId").equals(map.get("objectId")))
                    .filter(item -> ((Double.valueOf(String.valueOf(item.get("outAmt")).equals("null") ? "0" : String.valueOf(item.get("outAmt"))) != 0
                            && Double.valueOf(String.valueOf(item.get("outAmt")).equals("null") ? "0" : String.valueOf(item.get("outAmt"))) < 0)
                            || Double.valueOf(String.valueOf(item.get("sumAmtRec")).equals("null") ? "0" : String.valueOf(item.get("sumAmtRec"))) != 0
                            || Double.valueOf(String.valueOf(item.get("facAmt")).equals("null") ? "0" : String.valueOf(item.get("facAmt"))) != 0))
                    .collect(Collectors.toList());
            AtomicReference<Double> total = new AtomicReference<>(0.00);
            // 计算单用户的总计
            userArrearsItem.forEach(item -> {
                total.updateAndGet(v -> v + Double.valueOf(String.valueOf(item.get("facAmt")).equals("null") ? "0" : String.valueOf(item.get("facAmt")))
                        + Double.valueOf(String.valueOf(item.get("outAmt")).equals("null") ? "0" : String.valueOf(item.get("outAmt")))
                        - Double.valueOf(String.valueOf(item.get("sumAmtRec")).equals("null") ? "0" : String.valueOf(item.get("sumAmtRec"))));
            });
            map.put("arrears", total);*/
        }
        switch (String.valueOf(params.get("sort"))) {
            case "order":
                arrears = arrears.stream()
                        .sorted(Comparator.comparingDouble((Map map) -> Double.valueOf(String.valueOf(map.get("arrears")))))
                        .collect(Collectors.toList());
                break;
            case "down":
            default:
                arrears = arrears.stream()
                        .sorted(Comparator.comparingDouble((Map map) -> Double.valueOf(String.valueOf(map.get("arrears")))).reversed())
                        .collect(Collectors.toList());
                break;
        }
        if (Integer.parseInt(params.get("currentPage").toString()) == 1) {
            params.put("objectId", null);
            Map<String, Object> orderAmt = reportMapper.getOrderAmt(params);
            Map<String, Object> outBoundAmt = reportMapper.getOutboundAmt(params);
            Map<String, Object> startAmt = reportMapper.getStartAmt(params);
            Map<String, Object> incomeExpenditure = reportMapper.getIncomeExpenditure(params);

            Map<String, Object> sales = new HashMap<>();
            sales.put("facAmt", Double.valueOf(String.valueOf(orderAmt.get("orderAmt")).equals("null") ? "0" : String.valueOf(orderAmt.get("orderAmt")))
                    + Double.valueOf(String.valueOf(outBoundAmt.get("outboundAmt")).equals("null") ? "0" : String.valueOf(outBoundAmt.get("outboundAmt")))
                    + Double.valueOf(String.valueOf(startAmt.get("startAmt")).equals("null") ? "0" : String.valueOf(startAmt.get("startAmt"))));
            Map<String, Object> debt = new HashMap<>();
            debt.put("outAmt", Double.valueOf(String.valueOf(sales.get("facAmt")).equals("null") ? "0" : String.valueOf(sales.get("facAmt")))
                    - Double.valueOf(String.valueOf(incomeExpenditure.get("arrears")).equals("null") ? "0" : String.valueOf(incomeExpenditure.get("arrears"))));
            List<Map<String, Object>> overviewList = new ArrayList<>();
            overviewList.add(sales);
            overviewList.add(incomeExpenditure);
            overviewList.add(debt);
            overviewList.addAll(arrears);
            return ResponseResultUtil.success(overviewList);
        } else {
            return ResponseResultUtil.success(arrears);
        }
    }

    private static final Map<String, Class<?>> CLASS_MAP = ImmutableMap.<String, Class<?>>builder()
            /* 销售分析 */
            .put("saleTask", SaleTask.class)
            .put("returnSituation", ReturnSituation.class)
            .put("customerUnitPrice", CustomerUnitPrice.class)
//            .put("activityEffect1", ActivityEffect1.class)
//            .put("activityEffect2", ActivityEffect2.class)
//            .put("customizedWisdom1",CustomizedWisdom1.class)
//            .put("customizedWisdom2",CustomizedWisdom2.class)
            /* 收款分析 */
            .put("receivedTask", ReceivedTask.class)
            .put("arrearsInfo", ArrearsInfo.class)
            /* 客户分析 */
//            .put("budgetQuotation", BudgetQuotation.class)
            .put("potentialCustomerAnalysis", PotentialCustomerAnalysis.class)

            /* 客户来源 */
            .put("transaction", Transaction.class)
//            .put("offer", Offer.class)
            .put("potentialCustomerAnalysisFrom", PotentialCustomerAnalysisFrom.class)
            /* 产品分布 */
            .put("productDistribution", ProductDistribution.class)
            /* 部门成交 */
            .put("departmentTransactionRanking", DepartmentTransactionRanking.class)
            /* 部门收款 */
            .put("departmentCollectionRanking", DepartmentCollectionRanking.class)
            /* 业务员成交 */
            .put("staffTransactionRanking", StaffTransactionRanking.class)
            /* 业务员收款 */
            .put("staffCollectionRanking", StaffCollectionRanking.class)

            /* 店长简报部分 */
            /* 销售分析 */
            .put("saleTaskStaff", SaleTaskStaff.class)
            .put("returnSituationStaff", ReturnSituationStaff.class)
            .put("customerUnitPriceStaff", CustomerUnitPriceStaff.class)
            .put("customizedWisdomStaff1", CustomizedWisdomStaff1.class)
            .put("customizedWisdomStaff2", CustomizedWisdomStaff2.class)

            /* 收款分析 */
            .put("receivedTaskStaff", ReceivedTaskStaff.class)
            .put("arrearsInfoStaff", ArrearsInfoStaff.class)

            /* 收款分析 */
            .put("budgetQuotationStaff", BudgetQuotationStaff.class)
            .put("potentialCustomerAnalysisStaff", PotentialCustomerAnalysisStaff.class)

            /* 销售分析-部门品类 */
            .put("orgCategoryAmt", OrgCategoryAmt.class)
            .put("orgCategoryQty", OrgCategoryQty.class)

            /* 销售分析-部门单品 */
            .put("orgSpuAmt", OrgSpuAmt.class)
            .put("orgSpuQty", OrgSpuQty.class)

            /* 销售分析-业务员品类 */
            .put("staffCategoryAmt", StaffCategoryAmt.class)
            .put("staffCategoryQty", StaffCategoryQty.class)


            /* 销售分析-业务员单类 */
            .put("staffSpuAmt", StaffSpuAmt.class)
            .put("staffSpuQty", StaffSpuQty.class)

            /* 订单参考利润 - 品类排行 */
            .put("saleReferenceProfit1", categoryRanking.class)
            /* 订单参考利润 - 部门排行 */
            .put("saleReferenceProfit2", orgRanking.class)
            /* 订单参考利润 - 业务员排行 */
            .put("saleReferenceProfit3", staffRanking.class)

            /* 出库参考利润 - 品类排行 */
            .put("outReferenceProfit1", categoryRanking.class)
            /* 出库参考利润 - 部门排行 */
            .put("outReferenceProfit2", orgRanking.class)
            /* 出库参考利润 - 业务员排行 */
            .put("outReferenceProfit3", staffRanking.class)

            .build();

    private static final Map<String, String> TITLE_MAP = ImmutableMap.<String, String>builder()
            /* 销售分析 */
            .put("saleTask", "销售分析-销售任务")
            .put("returnSituation", "销售分析-退货情况")
            .put("customerUnitPrice", "销售分析-客单价")
//            .put("activityEffect1","销售分析-促销套餐活动效果")
//            .put("activityEffect2","销售分析-促销单品活动效果")
//            .put("customizedWisdom1","销售分析-定+智品类")
//            .put("customizedWisdom2","销售分析-定+定制类")
            /* 收款分析 */
            .put("receivedTask", "收款分析-收款任务")
            .put("arrearsInfo", "收款分析-欠款情况")
            /* 客户分析 */
//            .put("budgetQuotation", "客户分析-预算报价")
            .put("potentialCustomerAnalysis", "客户分析-潜客分析")
            /* 客户来源 */
            .put("transaction", "客户来源-成交情况")
//            .put("offer", "客户来源-报价情况")
            .put("potentialCustomerAnalysisFrom", "客户来源-潜客分析")
            /* 产品分布 */
            .put("productDistribution", "产品分布")
            /* 部门成交 */
            .put("departmentTransactionRanking", "部门成交排行")
            /* 部门收款 */
            .put("departmentCollectionRanking", "部门收款排行")
            /* 业务员成交 */
            .put("staffTransactionRanking", "业务员成交排行")
            /* 业务员收款 */
            .put("staffCollectionRanking", "业务员收款排行")

            /* 店长简报部分 */
            /* 销售分析 */
            .put("saleTaskStaff", "销售分析-销售任务")
            .put("returnSituationStaff", "销售分析-退货情况")
            .put("customerUnitPriceStaff", "销售分析-客单价")
            .put("customizedWisdomStaff1", "销售分析-定+智品类")
            .put("customizedWisdomStaff2", "销售分析-定+定制类")

            /* 收款分析 */
            .put("receivedTaskStaff", "收款分析-收款任务")
            .put("arrearsInfoStaff", "收款分析-欠款情况")

            /* 收款分析 */
            .put("budgetQuotationStaff", "客户分析-预算报价")
            .put("potentialCustomerAnalysisStaff", "客户分析-潜客分析")

            /*部门品类 */
            .put("orgCategoryAmt", "销售分析-部门品类金额")
            .put("orgCategoryQty", "销售分析-部门品类数量")

            /*部门单品 */
            .put("orgSpuAmt", "销售分析-部门单品金额")
            .put("orgSpuQty", "销售分析-部门单品数量")

            /*业务员品类 */
            .put("staffCategoryAmt", "销售分析-部门单品金额")
            .put("staffCategoryQty", "销售分析-部门单品数量")

            /*业务员单品 */
            .put("staffSpuAmt", "销售分析-业务员单品金额")
            .put("staffSpuQty", "销售分析-业务员单品数量")

            /* 订单参考利润 - 品类排行 */
            .put("saleReferenceProfit1", "订单参考利润-品类排行")
            /* 订单参考利润 - 部门排行 */
            .put("saleReferenceProfit2", "订单参考利润-部门排行")
            /* 订单参考利润 - 业务员排行 */
            .put("saleReferenceProfit3", "订单参考利润-业务员排行")

            /* 出库参考利润 - 品类排行 */
            .put("outReferenceProfit1", "出库参考利润-品类排行")
            /* 出库参考利润 - 部门排行 */
            .put("outReferenceProfit2", "出库参考利润-部门排行")
            /* 出库参考利润 - 业务员排行 */
            .put("outReferenceProfit3", "出库参考利润-业务员排行")


            .build();

    private static String getTotal(String str, Map<String, Object> data, List<String> calcStr) {
        String returnStr = str;
        Pattern dynamic = Pattern.compile(".*\\$\\{([A-Za-z0-9]+)\\}.*");
        Pattern dynamicLimitCount = Pattern.compile("\\$\\{([A-Za-z0-9]+)\\}");
        List<String> params = new ArrayList<>();
        Matcher m = dynamicLimitCount.matcher(str);
        while (m.find()) {
            params.add(m.group(1));
        }
        for (String it : params) {
            String value = data.get(it).toString();
            if (value != null && calcStr.contains(it)) {
                BigDecimal b = new BigDecimal(value);
                value = b.divide(BigDecimal.valueOf(10000), 2, RoundingMode.HALF_UP).toString();
            }
            returnStr = returnStr.replaceAll("\\$\\{" + it + "\\}", value);
        }
        return returnStr;
    }

    /**
     * @desc : 查询销售利润
     * @author : 洪旭东
     * @date : 2024-06-07 16:48
     */
    public ResponseResultVO<Map<String, Object>> getSaleProfit(Map<String, Object> param) {
        Map<String, Object> res = new HashMap<>();
        res.put("profit", reportMapper.getSaleProfit(param));
        res.put("dateProfit", reportMapper.getSaleProfitGroupByDate(param));
        param.put("limit", true);
        res.put("orgProfit", reportMapper.getSaleProfitGroupByOrg(param));
        res.put("staffProfit", reportMapper.getSaleProfitGroupByStaff(param));
        res.put("skuProfit", reportMapper.getSaleProfitGroupBySku(param));
        return ResponseResultUtil.success(res);
    }

    /**
     * @desc   : 查询销售利润 按日或按月
     * @author : 洪旭东
     * @date   : 2024-06-07 16:48
     */
//    public ResponseResultVO<List<Map<String, Object>>> getSaleProfitGroupByDate(Map<String, Object> param) {
//        return ResponseResultUtil.success(reportMapper.getSaleProfitGroupByDate(param));
//    }

    /**
     * @desc : 查询部门利润
     * @author : 洪旭东
     * @date : 2024-06-07 16:48
     */
    public ResponseResultVO<Map<String, Object>> getSaleProfitGroupByOrg(Map<String, Object> param) {
        Map<String, Object> res = new HashMap<>();
        res.put("profit", reportMapper.getSaleProfit(param));
        res.put("orgProfit", reportMapper.getSaleProfitGroupByOrg(param));
        return ResponseResultUtil.success(res);
    }

    /**
     * @desc : 查询业务员利润
     * @author : 洪旭东
     * @date : 2024-06-07 16:48
     */
    public ResponseResultVO<Map<String, Object>> getSaleProfitGroupByStaff(Map<String, Object> param) {
        Map<String, Object> res = new HashMap<>();
        res.put("profit", reportMapper.getSaleProfit(param));
        res.put("staffProfit", reportMapper.getSaleProfitGroupByStaff(param));
        return ResponseResultUtil.success(res);
    }

    /**
     * @desc : 查询商品利润
     * @author : 洪旭东
     * @date : 2024-06-07 16:48
     */
    public ResponseResultVO<Map<String, Object>> getSaleProfitGroupBySku(Map<String, Object> param) {
        Map<String, Object> res = new HashMap<>();
        res.put("profit", reportMapper.getSaleProfit(param));
        res.put("skuProfit", reportMapper.getSaleProfitGroupBySku(param));
        return ResponseResultUtil.success(res);
    }

    /**
     * @desc : 经营概况
     * @author : 常皓宁
     * @date : 2024/7/2 8:55
     */
    public ResponseResultVO<Map<String, Object>> getBusinessOverview(Map<String, Object> param) {
        if (param.get("querys") != null) {
            JSONObject querys = JSONObject.parseObject(param.get("querys").toString());
            param.put("querys", querys);
        }
        Map<String, Object> m = reportMapper.getBusinessOverview(param);
        JSONObject jObject = JSONObject.parseObject(m.get("f_query_business_overview").toString());
        return ResponseResultUtil.success(jObject);
    }

    /**
     * @desc   : 资金日记账
     * @author : 姜宁
     * @date   : 2024/7/19 15:27
     */
    public ResponseResultVO<PageList<Map<String, Object>>> getFundReportWeb(Map<String, Object> param) {
        // 校验分页参数
        if (param.get("pageSize") == null || param.get("currentPage") == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, "请检查分页参数!");
        }

        List<Object> objects = new ArrayList<>();
        if (param.get("macIds") instanceof ArrayList<?>) {
            for (Object o : (List<?>) param.get("macIds")) {
                objects.add(String.class.cast(o));
            }
        }
        if (objects.isEmpty()){
            param.remove("macIds");
        }
        // 获取资金日记账
        List<Map<String, Object>> list = reportMapper.getFundReportWeb(param);
        JSONObject jObject = JSONObject.parseObject(list.get(0).get("f_get_fund_report_web").toString());
        List dataList = jObject.get("data") != null ? JSONObject.parseArray(jObject.get("data").toString())
                .toJavaList(Map.class) : new ArrayList();

        // 定义返回值
        PageList data = new PageList<>();
        data.setPageSize((int) param.get("pageSize")).setCurrentPage((int) param.get("currentPage"))
                .setTotal(Long.parseLong(jObject.get("pageTotal").toString()))
                .setList(dataList);

        if ("查询成功".equals(jObject.get("message").toString())) {
            return ResponseResultUtil.success(data);
        } else {
            return ResponseResultUtil.error(666, jObject.get("message").toString());
        }
    }

}
