package com.junmp.jyzb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.junmp.jyzb.api.bean.dto.InventorySumDto;
import com.junmp.jyzb.api.bean.dto.largeScreenDto.*;
import com.junmp.jyzb.api.bean.dto.tjDto.*;
import com.junmp.jyzb.api.bean.query.InventorySumReq;
import com.junmp.jyzb.api.bean.query.OrderMainReq;
import com.junmp.jyzb.api.bean.query.QueryBusFormReq;
import com.junmp.jyzb.api.bean.query.tjReq.*;
import com.junmp.jyzb.api.bean.vo.TjOrgCountExportVo;
import com.junmp.jyzb.api.bean.vo.TjOrgEqsExportVo;
import com.junmp.jyzb.api.bean.vo.TjOrgPoliceExportVo;
import com.junmp.jyzb.api.bean.vo.TjOrgPriceExportVo;
import com.junmp.jyzb.api.constant.JYZBConstant;
import com.junmp.jyzb.entity.BusForm;
import com.junmp.jyzb.entity.InventorySummary;
import com.junmp.jyzb.entity.OrderMain;
import com.junmp.jyzb.entity.PubOrg;
import com.junmp.jyzb.mapper.*;
import com.junmp.jyzb.service.InventorySummaryService;
import com.junmp.jyzb.service.PubOrgService;
import com.junmp.jyzb.service.TjService;
import com.junmp.jyzb.utils.DateTimeUtil;
import com.junmp.jyzb.utils.SortingUtil;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.common.util.HttpServletUtil;
import com.junmp.v2.db.api.factory.PageFactory;
import com.junmp.v2.db.api.factory.PageResultFactory;
import com.junmp.v2.db.api.page.PageResult;
import com.junmp.v2.office.api.OfficeExcelApi;
import com.junmp.v2.office.api.bean.ExcelExportParam;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.Year;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Service
public class TjServiceImpl implements TjService {

    @Resource
    private InventorySummaryMapper inventorySummaryMapper;

    @Resource
    private PriceSumSummaryMapper priceSumSummaryMapper;

    @Resource
    private EquipmentCountSummaryMapper equipmentCountSummaryMapper;

    @Resource
    private LogSummaryMapper logSummaryMapper;

    @Resource
    private PoliceEquipmentMapper policeEquipmentMapper;
    @Resource
    private PubOrgService pubOrgService;
    @Resource
    private OfficeExcelApi officeExcelApi;

    @Resource
    private OrderMainMapper orderMainMapper;
    @Resource
    private BusFormMapper busFormMapper;

    @Resource
    private InventorySummaryService inventorySummaryService;
    //装备统计报表

    @Override
    public FinalTjOrgEqsDto test(TjOrgEqsReq req) {
        List<String> typeIdsList = req.getTypeIdsList();
        List<String> sizeNameList = req.getSizeNameList();
//        int size = typeIdsList.size();
//        int size1 = sizeNameList.size();
        boolean notNull = ObjectUtil.isNotNull(req.getTypeIdsList());
        boolean s = ObjectUtil.isNotNull(req.getSizeNameList());
//        System.out.println("yiyi = " + req.getTypeIdsList().isEmpty());
        System.out.println("yiyi = " + ObjectUtil.isEmpty(req.getTypeIdsList()));
//        System.out.println("yiyi = " + req.getTypeIdsList().isEmpty());
        return null;
    }



    @Override
    public PageResult<TjOrgEqsDto> GetTjData(TjOrgEqsReq req) {
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        //先拿到符合条件的组织机构，再遍历组织机构组成数据
        //（下一层数据组织机构数据）
       List<String> orgList= inventorySummaryMapper.getTotalData(String.valueOf(req.getOrgId()));
//       List<TjOrgEqsDto> allData=new ArrayList<>();

        Executor customExecutor = Executors.newFixedThreadPool(10); // 创建一个固定大小的线程池

        // 定义一个批处理大小，即每次处理的最大 orgId 数量
        int batchSize = 5;

// 将 orgList 分组，每组包含 batchSize 个 orgId
        List<List<String>> batches = new ArrayList<>();
        for (int i = 0; i < orgList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, orgList.size());
            List<String> batch = orgList.subList(i, endIndex);
            batches.add(batch);
        }

// 创建一个 CompletableFuture 的列表，每个 CompletableFuture 处理一个批次的 orgId
        List<CompletableFuture<List<TjOrgEqsDto>>> futures = batches.stream()
                .map(batch -> CompletableFuture.supplyAsync(() -> {
                    List<TjOrgEqsDto> results = new ArrayList<>();
                    for (String orgId : batch) {
                        // 调用 GetInvSum 方法，处理当前批次的所有 orgId
                        TjOrgEqsDto result = inventorySummaryMapper.GetInvSum(
                                orgId,
                                req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                                req.getSizeNameList().isEmpty() ? null : req.getSizesAsString(),
                                ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);
                        results.add(result);
                    }
                    return results;
                }, customExecutor)) // 使用自定义的 Executor
                .collect(Collectors.toList());

// 等待所有 CompletableFuture 完成，并收集结果
        List<TjOrgEqsDto> allData = futures.stream()
                .map(CompletableFuture::join)
                .flatMap(List::stream)
                .collect(Collectors.toList());

        if ((!req.getOrgId().equals(JYZBConstant.ORG_ID_PRODUCTION) || !req.getOrgId().equals(JYZBConstant.ORG_ID_TEST)) && pubOrg.getLevelFlag()!=1)
        {
            TjOrgEqsDto OrgDataSelf=inventorySummaryMapper.GetInvSelfSum(String.valueOf(req.getOrgId()),
                req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                req.getSizeNameList().isEmpty() ? null : req.getSizesAsString(),
                ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);
            OrgDataSelf.setLevel(0);
            OrgDataSelf.setOrgName(OrgDataSelf.getOrgName()+"本级");
            OrgDataSelf.setDName(OrgDataSelf.getDName()+"本级");
            TjOrgEqsDto OrgData = inventorySummaryMapper.GetSumLeve4(String.valueOf(req.getOrgId()),
                    req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                    req.getSizeNameList().isEmpty() ? null : req.getSizesAsString(),pubOrg.getLevelFlag(),
                    ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);
            if (ObjectUtil.isNotNull(OrgData)){

                OrgData.setLevel(1);
                OrgData.setOrgName(OrgData.getOrgName()+"直属下级");
                OrgData.setDName(OrgData.getDName()+"直属下级");
                allData.add(OrgDataSelf);//把本级数据加进去
                allData.add(OrgData);//把下级数据加进去
            }
        }
        //查询出来的组织机构进行判断，如果该组织机构下的装备装备总数为0，那么将该组织机构从list中移除
        if (ObjectUtil.isNull(req.getRemoveEmpty())|| req.getRemoveEmpty())
        {
            allData.removeIf(tjOrgEqsDto -> tjOrgEqsDto.getTotalNumber() == 0);
        }

        req.setColumn(StringUtils.isNotBlank(req.getColumn())? req.getColumn() : "createTime");
        req.setOrder(StringUtils.isNotBlank(req.getOrder())? req.getOrder() : "desc");
        //将组织机构进行排序后再进行返回
        if ((req.getColumn().equals("createTime") && req.getOrder().equals("desc")) ||
                (req.getColumn().equals("createTime") && req.getOrder().equals("asc"))){
            Comparator<TjOrgEqsDto> orgComparator = SortingUtil.createOrgComparator();
            Collections.sort(allData, orgComparator);
        }else {
            Comparator<Object> columnOrderComparator = SortingUtil.createColumnOrderComparator(req.getColumn(), req.getOrder());
            Collections.sort(allData, columnOrderComparator);
        }

        if (ObjectUtil.isNull(req.getPageNo()) && ObjectUtil.isNull(req.getPageSize())) {
            req.setPageNo(1L);
            req.setPageSize(10L);
        }
        Page<TjOrgEqsDto> page = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        long startIndex = (req.getPageNo() - 1) * req.getPageSize();
        long endIndex = Math.min(startIndex + req.getPageSize(), allData.size());
        List<TjOrgEqsDto> subList = allData.subList((int)startIndex, (int)endIndex);
        page.setRecords(subList);
        page.setTotal(allData.size());
        return PageResultFactory.createPageResult(page);
    }

    @Override
    public List<TjOrgEqsDto> GetTjDataList(TjOrgEqsReq req) {
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        //先拿到符合条件的组织机构，再遍历组织机构组成数据
        //（下一层数据组织机构数据）
        List<String> orgList= inventorySummaryMapper.getTotalData(String.valueOf(req.getOrgId()));
        List<TjOrgEqsDto> allData=new ArrayList<>();

        List<CompletableFuture<TjOrgEqsDto>> futures = orgList.stream()
                .map(orgId -> CompletableFuture.supplyAsync(() -> {
                    return inventorySummaryMapper.GetInvSum(
                            orgId,
                            req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                            req.getSizeNameList().isEmpty() ? null : req.getSizesAsString(),
                            ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);
                }))
                .collect(Collectors.toList());

        CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));

        allOf.join(); // 等待所有 CompletableFuture 完成

        allData = futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());

        if ((!req.getOrgId().equals(JYZBConstant.ORG_ID_PRODUCTION) || !req.getOrgId().equals(JYZBConstant.ORG_ID_TEST))
                && pubOrg.getLevelFlag()!=1)
        {
            TjOrgEqsDto OrgDataSelf=inventorySummaryMapper.GetInvSelfSum(String.valueOf(req.getOrgId()),
                    req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                    req.getSizeNameList().isEmpty() ? null : req.getSizesAsString(),
                    ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);
            OrgDataSelf.setLevel(0);
            OrgDataSelf.setOrgName(OrgDataSelf.getOrgName()+"本级");
            OrgDataSelf.setDName(OrgDataSelf.getDName()+"本级");
            TjOrgEqsDto OrgData = inventorySummaryMapper.GetSumLeve4(String.valueOf(req.getOrgId()),
                    req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                    req.getSizeNameList().isEmpty() ? null : req.getSizesAsString(),
                    pubOrg.getLevelFlag(),
                    ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);
            if (ObjectUtil.isNotNull(OrgData)){

                OrgData.setLevel(1);
                OrgData.setOrgName(OrgData.getOrgName()+"直属下级");
                OrgData.setDName(OrgData.getDName()+"直属下级");
                allData.add(OrgDataSelf);//把本级数据加进去
                allData.add(OrgData);//把下级数据加进去
            }
        }
        //查询出来的组织机构进行判断，如果该组织机构下的装备装备总数为0，那么将该组织机构从list中移除
        if (ObjectUtil.isNull(req.getRemoveEmpty())|| req.getRemoveEmpty())
        {
            allData.removeIf(tjOrgEqsDto -> tjOrgEqsDto.getTotalNumber() == 0);
        }

        req.setColumn(StringUtils.isNotBlank(req.getColumn())? req.getColumn() : "createTime");
        req.setOrder(StringUtils.isNotBlank(req.getOrder())? req.getOrder() : "desc");
        //将组织机构进行排序后再进行返回
        if ((req.getColumn().equals("createTime") && req.getOrder().equals("desc")) ||
                (req.getColumn().equals("createTime") && req.getOrder().equals("asc"))){
            Comparator<TjOrgEqsDto> orgComparator = SortingUtil.createOrgComparator();
            Collections.sort(allData, orgComparator);
        }else {
            Comparator<Object> columnOrderComparator = SortingUtil.createColumnOrderComparator(req.getColumn(), req.getOrder());
            Collections.sort(allData, columnOrderComparator);
        }
        return allData;
    }

    @Override
    public FinalTjOrgEqsDto TjOrgDataSum(TjOrgEqsReq req) {
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        FinalTjOrgEqsDto finalTjOrgEqsDto = new FinalTjOrgEqsDto();
        finalTjOrgEqsDto.setTotalNumber(0);
        finalTjOrgEqsDto.setCkStockNumber(0);
        finalTjOrgEqsDto.setCkOutboundNumber(0);
        finalTjOrgEqsDto.setDjgOutboundNumber(0);
        finalTjOrgEqsDto.setDjgStockNumber(0);
        finalTjOrgEqsDto.setDestructionNumber(0);
        finalTjOrgEqsDto.setBrokenNumber(0);
        List<String> orgList= inventorySummaryMapper.getTotalData(String.valueOf(req.getOrgId()));
        List<TjOrgEqsDto> allData=new ArrayList<>();

        List<CompletableFuture<TjOrgEqsDto>> futures = orgList.stream()
                .map(orgId -> CompletableFuture.supplyAsync(() -> {
                    return inventorySummaryMapper.GetInvSum(
                            orgId,
                            req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                            req.getSizeNameList().isEmpty() ? null : req.getSizesAsString(),
                            ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);
                }))
                .collect(Collectors.toList());

        CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));

        allOf.join(); // 等待所有 CompletableFuture 完成

        allData = futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());

        if ((!req.getOrgId().equals(JYZBConstant.ORG_ID_PRODUCTION) || !req.getOrgId().equals(JYZBConstant.ORG_ID_TEST))
                && pubOrg.getLevelFlag()!=1)
        {
            TjOrgEqsDto OrgDataSelf=inventorySummaryMapper.GetInvSelfSum(String.valueOf(req.getOrgId()),
                    req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                    req.getSizeNameList().isEmpty() ? null : req.getSizesAsString(),
                    ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);
            OrgDataSelf.setLevel(0);
            OrgDataSelf.setOrgName(OrgDataSelf.getOrgName()+"本级");
            OrgDataSelf.setDName(OrgDataSelf.getDName()+"本级");
            TjOrgEqsDto OrgData = inventorySummaryMapper.GetSumLeve4(String.valueOf(req.getOrgId()),
                    req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                    req.getSizeNameList().isEmpty() ? null : req.getSizesAsString(),
                    pubOrg.getLevelFlag(),
                    ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);
            if (ObjectUtil.isNotNull(OrgData)){

                OrgData.setLevel(1);
                OrgData.setOrgName(OrgData.getOrgName()+"直属下级");
                OrgData.setDName(OrgData.getDName()+"直属下级");
                allData.add(OrgDataSelf);//把本级数据加进去
                allData.add(OrgData);//把下级数据加进去
            }
        }
        for (TjOrgEqsDto tj:allData) {
            finalTjOrgEqsDto.setTotalNumber(finalTjOrgEqsDto.getTotalNumber()+ tj.getTotalNumber());
            finalTjOrgEqsDto.setCkStockNumber(finalTjOrgEqsDto.getCkStockNumber()+ tj.getCkStockNumber());
            finalTjOrgEqsDto.setCkOutboundNumber(finalTjOrgEqsDto.getCkOutboundNumber()+ tj.getCkOutboundNumber());
            finalTjOrgEqsDto.setDjgOutboundNumber(finalTjOrgEqsDto.getDjgOutboundNumber()+ tj.getDjgOutboundNumber());
            finalTjOrgEqsDto.setDjgStockNumber(finalTjOrgEqsDto.getDjgStockNumber()+ tj.getDjgStockNumber());
            finalTjOrgEqsDto.setDestructionNumber(finalTjOrgEqsDto.getDestructionNumber()+ tj.getDestructionNumber());
            finalTjOrgEqsDto.setBrokenNumber(finalTjOrgEqsDto.getBrokenNumber()+ tj.getBrokenNumber());
        }
        return finalTjOrgEqsDto;
    }



    //    @Override
    public List<TjOrgEqsDto> GetTjDataDetail(TjOrgEqsReq req) {
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        if (ObjectUtil.isNotNull(req.getColumn()) && !req.getColumn().trim().isEmpty() &&
                (req.getOrder().equalsIgnoreCase("asc")|| req.getOrder().equalsIgnoreCase("desc")) &&
                ObjectUtil.isNotNull(req.getOrder()) && !req.getOrder().trim().isEmpty()) {
            //修改字段，和数据库字段进行统一
            req.setColumn(req.getColumn().equals("createTime")
                    ? null : req.getColumn().replaceAll("[A-Z]", "_$0").toLowerCase());
            req.setOrder((req.getOrder().equals("desc")||req.getOrder().equals("asc"))
                    ? req.getOrder().toLowerCase() : null);
        }

        List<TjOrgEqsDto> allData=inventorySummaryMapper.getTotalDataDetail(String.valueOf(req.getOrgId()),
                req.getTypeIdsList(),req.getSizeNameList(),req.getLevelNum(),req.getLevel(),
                req.getColumn(),req.getOrder(),pubOrg.getLevelFlag(),ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);


        if (req.getRemoveEmpty())//如果需要删除数据为0的话，前端传true，否则保留数据为0
        {
            allData.removeIf(tjOrgEqsDto -> tjOrgEqsDto.getTotalNumber() == 0);
        }
        //将组织机构进行排序后再进行返回
        if (req.getColumn()==null){
            Comparator<TjOrgEqsDto> orgComparator = SortingUtil.createOrgComparator();
            Collections.sort(allData, orgComparator);
        }
        return allData;
    }

    //装备统计数据导出
    public void TjOrgEqsExport(TjOrgEqsReq req) {
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        //先拿到符合条件的组织机构，再遍历组织机构组成数据
        //（下一层数据组织机构数据）
        List<String> orgList= inventorySummaryMapper.getTotalData(String.valueOf(req.getOrgId()));
        List<TjOrgEqsDto> allData=new ArrayList<>();

        List<CompletableFuture<TjOrgEqsDto>> futures = orgList.stream()
                .map(orgId -> CompletableFuture.supplyAsync(() -> {
                    return inventorySummaryMapper.GetInvSum(
                            orgId,
                            req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                            req.getSizeNameList().isEmpty() ? null : req.getSizesAsString(),
                            ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);
                }))
                .collect(Collectors.toList());

        CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));

        allOf.join(); // 等待所有 CompletableFuture 完成

        allData = futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());
        if ((!req.getOrgId().equals(JYZBConstant.ORG_ID_PRODUCTION) || !req.getOrgId().equals(JYZBConstant.ORG_ID_TEST))
                && pubOrg.getLevelFlag()!=1)
        {
            TjOrgEqsDto OrgDataSelf=inventorySummaryMapper.GetInvSelfSum(String.valueOf(req.getOrgId()),
                    req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                    req.getSizeNameList().isEmpty() ? null : req.getSizesAsString(),
                    ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);
            OrgDataSelf.setLevel(0);
            OrgDataSelf.setOrgName(OrgDataSelf.getOrgName()+"本级");
            OrgDataSelf.setDName(OrgDataSelf.getDName()+"本级");

            TjOrgEqsDto OrgData = inventorySummaryMapper.GetSumLeve4(String.valueOf(req.getOrgId()),
                    req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                    req.getSizeNameList().isEmpty() ? null : req.getSizesAsString(),
                    pubOrg.getLevelFlag(),
                    ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);
            if (ObjectUtil.isNotNull(OrgData)){

                OrgData.setLevel(1);
                OrgData.setOrgName(OrgData.getOrgName()+"直属下级");
                OrgData.setDName(OrgData.getDName()+"直属下级");
                allData.add(OrgDataSelf);//把本级数据加进去
                allData.add(OrgData);//把下级数据加进去
            }
        }
        //查询出来的组织机构进行判断，如果该组织机构下的装备装备总数为0，那么将该组织机构从list中移除
        if (req.getRemoveEmpty()) {
            allData.removeIf(tjOrgEqsDto -> tjOrgEqsDto.getTotalNumber() == 0);
        }
        //将组织机构进行排序后再进行返回
        //对组织机构进行排序
        Map<String, List<?>> map = new LinkedHashMap<>();
        Comparator<TjOrgEqsDto> orgComparator = SortingUtil.createOrgComparator();
        Collections.sort(allData, orgComparator);
        for (TjOrgEqsDto tjOrgEqsDto:allData) {
            TjOrgEqsReq tjOrgEqsReq = new TjOrgEqsReq();
            BeanPlusUtil.copyProperties(req,tjOrgEqsReq);
            if (ObjectUtil.isNotNull(tjOrgEqsDto.getLevel()) &&(tjOrgEqsDto.getLevel()==1 || tjOrgEqsDto.getLevel()==0)){
                tjOrgEqsDto.setLevelNum(1);
                tjOrgEqsReq.setLevelNum(1);
            }else {
                tjOrgEqsDto.setLevelNum(0);
                tjOrgEqsReq.setLevelNum(0);
            }
            tjOrgEqsReq.setOrgId(tjOrgEqsDto.getOrgId());
            List<TjOrgEqsDto> tjOrgEqsDtos = GetTjDataDetail(tjOrgEqsReq);
            //将汇总合计数量存入
            TjOrgEqsDto vo = new TjOrgEqsDto();
            BeanPlusUtil.copyProperties(tjOrgEqsDto,vo);
            vo.setOrgName("合计");
            tjOrgEqsDtos.add(vo);
            List<TjOrgEqsExportVo> collect = tjOrgEqsDtos.stream().map(tjOrgEqsDto1 -> {
                TjOrgEqsExportVo tjOrgEqsExportVo = new TjOrgEqsExportVo();
                BeanPlusUtil.copyProperties(tjOrgEqsDto1, tjOrgEqsExportVo);
                return tjOrgEqsExportVo;
            }).collect(Collectors.toList());
            map.put(tjOrgEqsDto.getDName(),collect);// 将要导出的数据列表放入 map 中，其中 "dname" 是 sheet 的名称
            
        }


        HttpServletResponse response = HttpServletUtil.getResponse();
        ExcelExportParam excelExportParam = new ExcelExportParam();
        excelExportParam.setResponse(response); // 设置 HttpServletResponse
        excelExportParam.setClazz(TjOrgEqsExportVo.class); // 设置实体类的类型
        excelExportParam.setFileName("装备统计报表"); // 设置文件名
        excelExportParam.setExcelTypeEnum(ExcelTypeEnum.XLSX); // 设置 Excel 类型，比如 XLSX 或 XLS
        excelExportParam.setMap(map);
        // 调用方法进行导出
        officeExcelApi.easyExportManySheet(excelExportParam);

    }

    //查看装备统计详情
    @Override
    public List<InventorySumDto> TjOrgEqsDetailList(TjOrgEqsReq req) {
        req.setColumn(req.getColumn().equals("createTime")
                ? null : req.getColumn().replaceAll("[A-Z]", "_$0").toLowerCase());
        req.setOrder((req.getOrder().equals("desc")||req.getOrder().equals("asc"))
                ? req.getOrder().toLowerCase() : null);
        List<InventorySumDto> returnList=inventorySummaryMapper.TjOrgEqsDetail(req.getOrgId(),req.getTypeIdsList(),
                req.getSizeNameList(),req.getColumn(),req.getOrder(),ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);
        return returnList;
    }


//------------------------------------------------装备号型维度报表-------------------------------------------------
    @Override
    public PageResult<TjOrgEqsSizeDto> TjEqsSizeByOrg(TjOrgEqsSizeReq req) {
        List<TjOrgEqsSizeDto> tjOrgEqsSizeDtoList = inventorySummaryMapper.GetInvSumBySize(String.valueOf(req.getOrgId()),
                req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                req.getSizeNameList().isEmpty() ? null : req.getSizesAsString(),
                ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);
        //将组织机构进行排序后再进行返回
        if (!req.getColumn().equals("createTime")){
            Comparator<Object> columnOrderComparator = SortingUtil.createColumnOrderComparator(req.getColumn(), req.getOrder());
            Collections.sort(tjOrgEqsSizeDtoList, columnOrderComparator);
        }
        if (ObjectUtil.isNull(req.getPageNo()) && ObjectUtil.isNull(req.getPageSize())) {
            req.setPageNo(1L);
            req.setPageSize(10L);
        }
        //查询出来的组织机构进行判断，如果该组织机构下的装备装备总数为0，那么将该组织机构从list中移除
        if (ObjectUtil.isNull(req.getRemoveEmpty())|| req.getRemoveEmpty())
        {
            tjOrgEqsSizeDtoList.removeIf(tjOrgEqsDto -> tjOrgEqsDto.getTotalNumber() == 0);
        }
        Page<TjOrgEqsSizeDto> page = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        long startIndex = (req.getPageNo() - 1) * req.getPageSize();
        long endIndex = Math.min(startIndex + req.getPageSize(), tjOrgEqsSizeDtoList.size());
        List<TjOrgEqsSizeDto> subList = tjOrgEqsSizeDtoList.subList((int)startIndex, (int)endIndex);
        page.setRecords(subList);
        page.setTotal(tjOrgEqsSizeDtoList.size());
        return PageResultFactory.createPageResult(page);
    }

    @Override
    public FinalTjOrgEqsDto TjEqsSizeByOrgSum(TjOrgEqsSizeReq req) {
        Integer totalNumber = 0;
        Integer ckStockNumber = 0;
        Integer ckOutboundNumber = 0;
        Integer djgOutboundNumber = 0;
        Integer djgStockNumber = 0;
        Integer brokenNumber = 0;
        Integer destructionNumber = 0;

        List<TjOrgEqsSizeDto> tjOrgEqsSizeDtoList = inventorySummaryMapper.GetInvSumBySize(String.valueOf(req.getOrgId()),
                req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                req.getSizeNameList().isEmpty() ? null : req.getSizesAsString(),
                ObjectUtil.isNotEmpty(req.getTypeName())?req.getTypeName():null);
        for (TjOrgEqsSizeDto tj : tjOrgEqsSizeDtoList) {
            totalNumber += tj.getTotalNumber();
            ckStockNumber += tj.getCkStockNumber();
            ckOutboundNumber += tj.getCkOutboundNumber();
            djgOutboundNumber += tj.getDjgOutboundNumber();
            djgStockNumber += tj.getDjgStockNumber();
            destructionNumber += tj.getDestructionNumber();
            brokenNumber += tj.getBrokenNumber();
        }
        FinalTjOrgEqsDto finalTjOrgEqsDto = new FinalTjOrgEqsDto();
        finalTjOrgEqsDto.setTotalNumber(totalNumber);
        finalTjOrgEqsDto.setCkStockNumber(ckStockNumber);
        finalTjOrgEqsDto.setCkOutboundNumber(ckOutboundNumber);
        finalTjOrgEqsDto.setDjgOutboundNumber(djgOutboundNumber);
        finalTjOrgEqsDto.setDjgStockNumber(djgStockNumber);
        finalTjOrgEqsDto.setDestructionNumber(destructionNumber);
        finalTjOrgEqsDto.setBrokenNumber(brokenNumber);
        return finalTjOrgEqsDto;
    }



//------------------------------------------------财务统计报表--------------------------------------------------------


    public PageResult<TjOrgPriceDto> TjOrgPrice(TjOrgPriceReq req) {
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        //先拿到符合条件的组织机构，再遍历组织机构组成数据
        //（下一层数据组织机构数据）
        List<String> orgList= inventorySummaryMapper.getTotalData(String.valueOf(req.getOrgId()));
        List<TjOrgPriceDto> tjOrgPriceDtoList=new ArrayList<>();
        List<CompletableFuture<TjOrgPriceDto>> futures = orgList.stream()
                .map(orgId -> CompletableFuture.supplyAsync(() ->
                        priceSumSummaryMapper.TjOrgPrice(orgId, req.getYear(),req.getTypeIdsList(),req.getSizeNameList(),req.getTypeName() )
                ))
                .collect(Collectors.toList());
// 等待所有 CompletableFuture 完成
        CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
//
        // 等待所有 CompletableFuture 完成
        allOf.join();
        tjOrgPriceDtoList = futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());

        if ((!req.getOrgId().equals(JYZBConstant.ORG_ID_PRODUCTION) || !req.getOrgId().equals(JYZBConstant.ORG_ID_TEST))
                && pubOrg.getLevelFlag()!=1){
            //获取本级数据
            System.out.println("开始本级数据 = " + new Date());
            TjOrgPriceDto OrgDataSelf=priceSumSummaryMapper.TjOrgPriceBySelf(req.getOrgId(), req.getYear(),req.getTypeIdsList(),
                    req.getSizeNameList(),req.getTypeName());
            OrgDataSelf.setLevel(0);
            OrgDataSelf.setOrgName(OrgDataSelf.getOrgName()+"本级");
            OrgDataSelf.setDName(OrgDataSelf.getDName()+"本级");
            OrgDataSelf = fillingEqsEmptyData(OrgDataSelf);
            System.out.println("结束本级数据 = " + new Date());
            System.out.println("开始下级数据 = " + new Date());
            //获取下级数据
            TjOrgPriceDto OrgData=priceSumSummaryMapper.TjOrgPriceLeve4(req.getOrgId(), req.getYear(),req.getTypeIdsList(),
                    req.getSizeNameList(),pubOrg.getLevelFlag(),req.getTypeName());
            System.out.println("结束下级数据 = " + new Date());
            if (ObjectUtil.isNotNull(OrgData)){

                OrgData.setLevel(1);
                OrgData.setOrgName(OrgData.getOrgName()+"直属下级");
                OrgData.setDName(OrgData.getDName()+"直属下级");
                OrgData=fillingEqsEmptyData(OrgData);
                tjOrgPriceDtoList.add(OrgData);//把直属下级数据加进去
                tjOrgPriceDtoList.add(OrgDataSelf);//把本级数据加进去
            }
        }

        //查询出来的组织机构进行判断，如果该组织机构下的装备装备总数为0，那么将该组织机构从list中移除
        if (req.getRemoveEmpty()){
            tjOrgPriceDtoList.removeIf(tjOrgEqsDto -> tjOrgEqsDto.getStartNum() == 0 && tjOrgEqsDto.getEndNum() == 0
                    && tjOrgEqsDto.getDestoryNum()==0);
        }

        //对组织机构进行排序
        if ((req.getColumn().equals("createTime") && req.getOrder().equals("desc")) ||
                (req.getColumn().equals("createTime") && req.getOrder().equals("asc"))){
            Comparator<TjOrgPriceDto> orgComparator = SortingUtil.createOrgComparator();
            Collections.sort(tjOrgPriceDtoList, orgComparator);
        }else {
            Comparator<Object> columnOrderComparator = SortingUtil.createColumnOrderComparator(req.getColumn(), req.getOrder());
            Collections.sort(tjOrgPriceDtoList, columnOrderComparator);
        }
        Page<TjOrgPriceDto> page = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        if (ObjectUtil.isNull(req.getPageNo()) && ObjectUtil.isNull(req.getPageSize())) {
            req.setPageNo(1L);
            req.setPageSize(10L);
        }
        long startIndex = (req.getPageNo() - 1) * req.getPageSize();
        long endIndex = Math.min(startIndex + req.getPageSize(), tjOrgPriceDtoList.size());
        List<TjOrgPriceDto> subList = tjOrgPriceDtoList.subList((int) startIndex, (int)endIndex);
//        List<TjOrgPriceDto> subList = tjOrgPriceDtoList.subList((int) ((req.getPageNo()-1)*req.getPageSize()), req.getPageSize().intValue());
        page.setTotal(tjOrgPriceDtoList.size());
        page.setRecords(subList);
        return PageResultFactory.createPageResult(page);
    }

    //添加null数据，将null改成0以防空指针
    public TjOrgPriceDto fillingEqsEmptyData(TjOrgPriceDto OrgData){
        OrgData.setAddNum(ObjectUtil.isNull(OrgData.getAddNum())?0:OrgData.getAddNum());
        OrgData.setEndNum(ObjectUtil.isNull(OrgData.getEndNum())?0:OrgData.getEndNum());
        OrgData.setStartNum(ObjectUtil.isNull(OrgData.getStartNum())?0:OrgData.getStartNum());
        OrgData.setDestoryNum(ObjectUtil.isNull(OrgData.getDestoryNum())?0:OrgData.getDestoryNum());
        OrgData.setStartPrice(ObjectUtil.isNull(OrgData.getStartPrice())?BigDecimal.ZERO:OrgData.getStartPrice());
        OrgData.setEndPrice(ObjectUtil.isNull(OrgData.getEndPrice())?BigDecimal.ZERO:OrgData.getEndPrice());
        OrgData.setAddPrice(ObjectUtil.isNull(OrgData.getAddPrice())?BigDecimal.ZERO:OrgData.getAddPrice());
        OrgData.setDestoryPrice(ObjectUtil.isNull(OrgData.getDestoryPrice())?BigDecimal.ZERO:OrgData.getDestoryPrice());
        return OrgData;
    }

    @Override
    public FinalTjOrgPriceDto TjOrgPriceSum(TjOrgPriceReq req) {
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        FinalTjOrgPriceDto finalTjOrgPriceDto = new FinalTjOrgPriceDto();
        finalTjOrgPriceDto.setAddNum(0);
        finalTjOrgPriceDto.setStartNum(0);
        finalTjOrgPriceDto.setEndNum(0);
        finalTjOrgPriceDto.setDestoryNum(0);
        finalTjOrgPriceDto.setAddPrice(BigDecimal.ZERO);
        finalTjOrgPriceDto.setStartPrice(BigDecimal.ZERO);
        finalTjOrgPriceDto.setEndPrice(BigDecimal.ZERO);
        finalTjOrgPriceDto.setDestoryPrice(BigDecimal.ZERO);
        List<String> orgList= inventorySummaryMapper.getTotalData(String.valueOf(req.getOrgId()));

        List<TjOrgPriceDto> tjOrgPriceDtoList=new ArrayList<>();

        //根据条件查询财务汇总表
        List<CompletableFuture<TjOrgPriceDto>> futures = orgList.stream()
                .map(orgId -> CompletableFuture.supplyAsync(() ->
                        priceSumSummaryMapper.TjOrgPrice(orgId, req.getYear(),req.getTypeIdsList(),req.getSizeNameList(), req.getTypeName() )
                ))
                .collect(Collectors.toList());

        CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        // 等待所有 CompletableFuture 完成
        allOf.join();

        tjOrgPriceDtoList = futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());


        if ((!req.getOrgId().equals(JYZBConstant.ORG_ID_PRODUCTION) || !req.getOrgId().equals(JYZBConstant.ORG_ID_TEST))
                && pubOrg.getLevelFlag()!=1){
            //获取本级数据
            TjOrgPriceDto OrgDataSelf=priceSumSummaryMapper.TjOrgPriceBySelf(req.getOrgId(), req.getYear(),req.getTypeIdsList(),
                    req.getSizeNameList(), req.getTypeName());
            OrgDataSelf.setLevel(0);
            OrgDataSelf.setOrgName(OrgDataSelf.getOrgName()+"本级");
            OrgDataSelf.setDName(OrgDataSelf.getDName()+"本级");
            OrgDataSelf = fillingEqsEmptyData(OrgDataSelf);
            //获取下级数据
            TjOrgPriceDto OrgData=priceSumSummaryMapper.TjOrgPriceLeve4(req.getOrgId(), req.getYear(),req.getTypeIdsList(),
                    req.getSizeNameList(),pubOrg.getLevelFlag(),req.getTypeName());
            if (ObjectUtil.isNotNull(OrgData)){

                OrgData.setLevel(1);
                OrgData.setOrgName(OrgData.getOrgName()+"直属下级");
                OrgData.setDName(OrgData.getDName()+"直属下级");
                OrgData=fillingEqsEmptyData(OrgData);
                tjOrgPriceDtoList.add(OrgData);//把直属下级数据加进去
                tjOrgPriceDtoList.add(OrgDataSelf);//把本级数据加进去
            }
        }

        for (TjOrgPriceDto tj:tjOrgPriceDtoList) {
            finalTjOrgPriceDto.setAddNum(finalTjOrgPriceDto.getAddNum()+Math.abs(tj.getAddNum()));
            finalTjOrgPriceDto.setStartNum(finalTjOrgPriceDto.getStartNum()+tj.getStartNum());
            finalTjOrgPriceDto.setEndNum(finalTjOrgPriceDto.getEndNum()+tj.getEndNum());
            finalTjOrgPriceDto.setDestoryNum(finalTjOrgPriceDto.getDestoryNum()+tj.getDestoryNum());
            finalTjOrgPriceDto.setAddPrice(finalTjOrgPriceDto.getAddPrice().add(tj.getAddPrice()));
            finalTjOrgPriceDto.setStartPrice(finalTjOrgPriceDto.getStartPrice().add(tj.getStartPrice()));
            finalTjOrgPriceDto.setEndPrice(finalTjOrgPriceDto.getEndPrice().add(tj.getEndPrice()));
            finalTjOrgPriceDto.setDestoryPrice(finalTjOrgPriceDto.getDestoryPrice().add(tj.getDestoryPrice()));
        }
        return finalTjOrgPriceDto;
    }


//    @Override
//    public List<TjOrgPriceDto> TjOrgPriceDetail(TjOrgPriceReq req) {
//
//        List<TjOrgPriceDto> tjOrgPriceDtoList = priceSumSummaryMapper.TjOrgPriceTotalNum(req.getOrgId(), req.getYear(),
//                req.getTypeIdsList(),req.getSizeNameList(),req.getLevelNum(),req.getLevel());
//        if (req.getRemoveEmpty()){
//            tjOrgPriceDtoList.removeIf(tjOrgEqsDto -> tjOrgEqsDto.getStartNum() == 0 && tjOrgEqsDto.getEndNum() == 0
//                    && tjOrgEqsDto.getDestoryNum()==0);
//        }
//        return tjOrgPriceDtoList;
//    }

    @Override
    public List<TjOrgPriceDto> TjOrgPriceDetail(TjOrgPriceReq req) {
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        if (ObjectUtil.isNotNull(req.getColumn()) && !req.getColumn().trim().isEmpty() &&
                (req.getOrder().equalsIgnoreCase("asc")|| req.getOrder().equalsIgnoreCase("desc")) &&
                ObjectUtil.isNotNull(req.getOrder()) && !req.getOrder().trim().isEmpty()) {
            //修改字段，和数据库字段进行统一
            req.setColumn(req.getColumn().equals("createTime")
                    ? null : req.getColumn().replaceAll("[A-Z]", "_$0").toLowerCase());
            req.setOrder((req.getOrder().equals("desc")||req.getOrder().equals("asc"))
                    ? req.getOrder().toLowerCase() :null );
        }
        List<TjOrgPriceDto> allData=priceSumSummaryMapper.getTotalPriceDetail(req.getOrgId(), req.getYear(),
                req.getTypeIdsList(),req.getSizeNameList(),req.getLevelNum(),req.getLevel(),
                req.getColumn(),req.getOrder(),pubOrg.getLevelFlag(), req.getTypeName());
        if (req.getRemoveEmpty()){
            allData.removeIf(tjOrgEqsDto -> tjOrgEqsDto.getStartNum() == 0 && tjOrgEqsDto.getEndNum() == 0
                    && tjOrgEqsDto.getDestoryNum()==0);
        }

        return allData;
    }


    @Override
    public void TjOrgPriceExport(TjOrgPriceReq req) {
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        //先拿到符合条件的组织机构，再遍历组织机构组成数据
        //（下一层数据组织机构数据）
        List<String> orgList= inventorySummaryMapper.getTotalData(String.valueOf(req.getOrgId()));
        List<TjOrgPriceDto> tjOrgPriceDtoList=new ArrayList<>();
        List<CompletableFuture<TjOrgPriceDto>> futures = orgList.stream()
                .map(orgId -> CompletableFuture.supplyAsync(() ->
                        priceSumSummaryMapper.TjOrgPrice(orgId, req.getYear(),req.getTypeIdsList(),req.getSizeNameList(),req.getTypeName() )
                ))
                .collect(Collectors.toList());
// 等待所有 CompletableFuture 完成
        CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
//
        // 等待所有 CompletableFuture 完成
        allOf.join();

        if ((!req.getOrgId().equals(JYZBConstant.ORG_ID_PRODUCTION) || !req.getOrgId().equals(JYZBConstant.ORG_ID_TEST))
                && pubOrg.getLevelFlag()!=1){
            //获取本级数据
            TjOrgPriceDto OrgDataSelf=priceSumSummaryMapper.TjOrgPriceBySelf(req.getOrgId(), req.getYear(),req.getTypeIdsList(),
                    req.getSizeNameList(),req.getTypeName());
            OrgDataSelf.setLevel(0);
            OrgDataSelf.setOrgName(OrgDataSelf.getOrgName()+"本级");
            OrgDataSelf.setDName(OrgDataSelf.getDName()+"本级");
            OrgDataSelf = fillingEqsEmptyData(OrgDataSelf);
            //获取下级数据
            TjOrgPriceDto OrgData=priceSumSummaryMapper.TjOrgPriceLeve4(req.getOrgId(), req.getYear(),req.getTypeIdsList(),
                    req.getSizeNameList(),pubOrg.getLevelFlag(),req.getTypeName());
            if (ObjectUtil.isNotNull(OrgData)){

                OrgData.setLevel(1);
                OrgData.setOrgName(OrgData.getOrgName()+"直属下级");
                OrgData.setDName(OrgData.getDName()+"直属下级");
                OrgData=fillingEqsEmptyData(OrgData);
                tjOrgPriceDtoList.add(OrgData);//把直属下级数据加进去
                tjOrgPriceDtoList.add(OrgDataSelf);//把本级数据加进去
            }
        }
        tjOrgPriceDtoList = futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());


        //查询出来的组织机构进行判断，如果该组织机构下的装备装备总数为0，那么将该组织机构从list中移除
        if (req.getRemoveEmpty()){
            tjOrgPriceDtoList.removeIf(tjOrgEqsDto -> tjOrgEqsDto.getStartNum() == 0 && tjOrgEqsDto.getEndNum() == 0
                    && tjOrgEqsDto.getDestoryNum()==0);
        }

        //对组织机构进行排序
        Map<String, List<?>> map = new LinkedHashMap<>();
        Comparator<TjOrgPriceDto> orgComparator = SortingUtil.createOrgComparator();
        Collections.sort(tjOrgPriceDtoList, orgComparator);
        for (TjOrgPriceDto dto: tjOrgPriceDtoList) {
            TjOrgPriceReq tjOrgPriceReq = new TjOrgPriceReq();
            BeanPlusUtil.copyProperties(req,tjOrgPriceReq);
            if (ObjectUtil.isNotNull(dto.getLevel()) &&(dto.getLevel()==1 || dto.getLevel()==0)){
                dto.setLevelNum(1);
                tjOrgPriceReq.setLevelNum(1);
            }else {
                dto.setLevelNum(0);
                tjOrgPriceReq.setLevelNum(0);
            }
            tjOrgPriceReq.setOrgId(dto.getOrgId());
            List<TjOrgPriceDto> tjOrgPriceDtos = TjOrgPriceDetail(tjOrgPriceReq);
            TjOrgPriceDto vo = new TjOrgPriceDto();
            BeanPlusUtil.copyProperties(dto,vo);
            vo.setTypeName("合计");
            tjOrgPriceDtos.add(vo);
            List<TjOrgPriceExportVo> collect = tjOrgPriceDtos.stream().map(tjOrgPriceDto -> {
                TjOrgPriceExportVo tjOrgPriceExportVo = new TjOrgPriceExportVo();
                BeanPlusUtil.copyProperties(tjOrgPriceDto, tjOrgPriceExportVo);
                return tjOrgPriceExportVo;
            }).collect(Collectors.toList());
            map.put(dto.getDName(),collect);// 将要导出的数据列表放入 map 中，其中 "orgName" 是 sheet 的名称
        }

        HttpServletResponse response = HttpServletUtil.getResponse();
        ExcelExportParam excelExportParam = new ExcelExportParam();
        excelExportParam.setResponse(response); // 设置 HttpServletResponse
        excelExportParam.setClazz(TjOrgPriceExportVo.class); // 设置实体类的类型
        excelExportParam.setFileName("财务统计报表"); // 设置文件名
        excelExportParam.setExcelTypeEnum(ExcelTypeEnum.XLSX); // 设置 Excel 类型，比如 XLSX 或 XLS
        excelExportParam.setMap(map);
        // 调用方法进行导出
        officeExcelApi.easyExportManySheet(excelExportParam);
    }



    //-------------------------------------------使用统计报表----------------------------------------------------------

    @Override
    public PageResult<TjOrgCountDto> TjOrgCount(TjOrgCountReq req) {

        //先拿到符合条件的组织机构，再遍历组织机构组成数据
        //（下一层数据组织机构数据）
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        List<String> orgList= inventorySummaryMapper.getTotalData(String.valueOf(req.getOrgId()));
        List<TjOrgCountDto> tjOrgCountList=new ArrayList<>();

        if (StringUtils.isNotEmpty(req.getStartTime())){
            req.setStartTime(req.getStartTime()+"-01 00:00:00");
        }
        if (StringUtils.isNotEmpty(req.getEndTime())){
            req.setEndTime(DateTimeUtil.getLastDayOfMonth(req.getEndTime()));
        }

        List<CompletableFuture<TjOrgCountDto>> futures = orgList.stream()
                .map(orgId -> CompletableFuture.supplyAsync(() ->
                        equipmentCountSummaryMapper.TjOrgCount(orgId,
                                req.getTypeIdsList(), req.getSizeNameList(),
                                req.getTypeParentId(),req.getTypeName(),req.getStartTime(),req.getEndTime()))
                )
                .collect(Collectors.toList());
        CompletableFuture<Void> allOf = CompletableFuture.allOf( futures.toArray(new CompletableFuture[0]));


        allOf.join();
        tjOrgCountList = futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());

        if ((!req.getOrgId().equals(JYZBConstant.ORG_ID_PRODUCTION) || !req.getOrgId().equals(JYZBConstant.ORG_ID_TEST))
                && pubOrg.getLevelFlag()!=1){
            TjOrgCountDto OrgDataSelf=equipmentCountSummaryMapper.TjOrgCountSelf(req.getOrgId(),
                    req.getTypeIdsList(),req.getSizeNameList(),req.getTypeParentId(),
                    req.getTypeName(),req.getStartTime(),req.getEndTime());
            OrgDataSelf.setLevel(0);
            OrgDataSelf.setOrgName(OrgDataSelf.getOrgName()+"本级");
            OrgDataSelf.setDName(OrgDataSelf.getDName()+"本级");
            OrgDataSelf=fillingPriceEmptyData(OrgDataSelf);
            TjOrgCountDto OrgData =equipmentCountSummaryMapper.TjOrgCountleve4(req.getOrgId(),
                    req.getTypeIdsList(),req.getSizeNameList(),req.getTypeParentId(),
                    pubOrg.getLevelFlag(),req.getTypeName(),req.getStartTime(),req.getEndTime());
            if (ObjectUtil.isNotNull(OrgData)){

                OrgData.setLevel(1);
                OrgData.setOrgName(OrgData.getOrgName()+"直属下级");
                OrgData.setDName(OrgData.getDName()+"直属下级");
                OrgData=fillingPriceEmptyData(OrgData);
                tjOrgCountList.add(OrgData);
                tjOrgCountList.add(OrgDataSelf);
            }
        }

        //查询出来的组织机构进行判断，如果该组织机构下的装备装备总数为0，那么将该组织机构从list中移除
        if (req.getRemoveEmpty()){
            tjOrgCountList.removeIf(TjOrgCountDto -> TjOrgCountDto.getNumber() == 0 );
        }

        //对组织机构进行排序
        //判断是否有排序规则，如果有排序规则且排序规则不是create_time desc，那么直接按照排序规则进行排序，否则按照默认的组织机构code编码进行排序
        if ((req.getColumn().equals("createTime") && req.getOrder().equals("desc")) ||
                (req.getColumn().equals("createTime") && req.getOrder().equals("asc"))){
            Comparator<TjOrgCountDto> orgComparator = SortingUtil.createOrgComparator();
            Collections.sort(tjOrgCountList, orgComparator);
        }else {
            Comparator<Object> columnOrderComparator = SortingUtil.createColumnOrderComparator(req.getColumn(), req.getOrder());
            Collections.sort(tjOrgCountList, columnOrderComparator);
        }

        Page<TjOrgCountDto> page = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        if (ObjectUtil.isNull(req.getPageNo()) && ObjectUtil.isNull(req.getPageSize())) {
            req.setPageNo(1L);
            req.setPageSize(10L);
        }
        long startIndex = (req.getPageNo() - 1) * req.getPageSize();
        long endIndex = Math.min(startIndex + req.getPageSize(), tjOrgCountList.size());
        List<TjOrgCountDto> subList = tjOrgCountList.subList((int) startIndex, (int)endIndex);
        page.setTotal(tjOrgCountList.size());
        page.setRecords(subList);
        return PageResultFactory.createPageResult(page);
    }
    //添加null数据，将null改成0以防空指针
    public TjOrgCountDto fillingPriceEmptyData(TjOrgCountDto orgData){
        orgData.setNumber(ObjectUtil.isNull(orgData.getNumber()) ? 0 : orgData.getNumber());
        orgData.setUseCount(ObjectUtil.isNull(orgData.getUseCount()) ? 0 : orgData.getUseCount());
        return orgData;
    }

    @Override
    public FinalTjOrgCountDto TjOrgCountSum(TjOrgCountReq req) {

        FinalTjOrgCountDto finalTjOrgCountDto=new FinalTjOrgCountDto();
        finalTjOrgCountDto.setFixCount(0);
        finalTjOrgCountDto.setUseCount(0);
        finalTjOrgCountDto.setNumber(0);
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        List<String> orgList= inventorySummaryMapper.getTotalData(String.valueOf(req.getOrgId()));
        List<TjOrgCountDto> tjOrgCountList=new ArrayList<>();
        if (StringUtils.isNotEmpty(req.getStartTime())){
            req.setStartTime(req.getStartTime()+"-01 00:00:00");
        }
        if (StringUtils.isNotEmpty(req.getEndTime())){
            req.setEndTime(DateTimeUtil.getLastDayOfMonth(req.getEndTime()));
        }
        List<CompletableFuture<TjOrgCountDto>> futures = orgList.stream()
                .map(orgId -> CompletableFuture.supplyAsync(() ->
                        equipmentCountSummaryMapper.TjOrgCount(orgId,
                                req.getTypeIdsList(), req.getSizeNameList(),
                                req.getTypeParentId(),req.getTypeName(), req.getStartTime(), req.getEndTime()))
                )
                .collect(Collectors.toList());
// 等待所有 CompletableFuture 完成
        CompletableFuture<Void> allOf = CompletableFuture.allOf( futures.toArray(new CompletableFuture[0]));


        allOf.join();
        tjOrgCountList = futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());

        if ((!req.getOrgId().equals(JYZBConstant.ORG_ID_PRODUCTION) || !req.getOrgId().equals(JYZBConstant.ORG_ID_TEST))
                && pubOrg.getLevelFlag()!=1){
            TjOrgCountDto OrgDataSelf=equipmentCountSummaryMapper.TjOrgCountSelf(req.getOrgId(),
                    req.getTypeIdsList(),req.getSizeNameList(),req.getTypeParentId(),
                    req.getTypeName(),req.getStartTime(),req.getEndTime());
            OrgDataSelf.setLevel(0);
            OrgDataSelf.setOrgName(OrgDataSelf.getOrgName()+"本级");
            OrgDataSelf.setDName(OrgDataSelf.getDName()+"本级");
            OrgDataSelf=fillingPriceEmptyData(OrgDataSelf);
            TjOrgCountDto OrgData =equipmentCountSummaryMapper.TjOrgCountleve4(req.getOrgId(),
                    req.getTypeIdsList(),req.getSizeNameList(),req.getTypeParentId(),
                    pubOrg.getLevelFlag(),req.getTypeName(),req.getStartTime(),req.getEndTime());
            if (ObjectUtil.isNotNull(OrgData)){

                OrgData.setLevel(1);
                OrgData.setOrgName(OrgData.getOrgName()+"直属下级");
                OrgData.setDName(OrgData.getDName()+"直属下级");
                OrgData=fillingPriceEmptyData(OrgData);
                tjOrgCountList.add(OrgData);
                tjOrgCountList.add(OrgDataSelf);
            }
        }
        for (TjOrgCountDto tj:tjOrgCountList) {
            tj.setUseCount(ObjectUtil.isNull(tj.getUseCount())?0: tj.getUseCount());
            tj.setNumber(ObjectUtil.isNull(tj.getNumber())?0: tj.getNumber());
            finalTjOrgCountDto.setUseCount(finalTjOrgCountDto.getUseCount()+ tj.getUseCount());
            finalTjOrgCountDto.setNumber(finalTjOrgCountDto.getNumber()+ tj.getNumber());
        }
        return finalTjOrgCountDto;
    }

//    @Override
    public List<TjOrgCountDto> TjOrgCountDetail(TjOrgCountReq req) {
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        if (ObjectUtil.isNotNull(req.getColumn()) && req.getColumn().equals("createTime")){
            req.setColumn(null);
        }
        if (ObjectUtil.isNotNull(req.getColumn()) && !req.getColumn().trim().isEmpty() &&
                (req.getOrder().equalsIgnoreCase("asc")|| req.getOrder().equalsIgnoreCase("desc")) &&
                ObjectUtil.isNotNull(req.getOrder()) && !req.getOrder().trim().isEmpty()) {
            //修改字段，和数据库字段进行统一
            req.setColumn(req.getColumn().replaceAll("[A-Z]", "_$0").toLowerCase());
            req.setOrder(req.getOrder().toLowerCase());
        }

        if (StringUtils.isNotEmpty(req.getStartTime())){
            req.setStartTime(req.getStartTime()+"-01 00:00:00");
        }
        if (StringUtils.isNotEmpty(req.getEndTime())){
            req.setEndTime(DateTimeUtil.getLastDayOfMonth(req.getEndTime()));
        }
        List<TjOrgCountDto> tjOrgCountDtoList=equipmentCountSummaryMapper.TjOrgCountTotalNum(req.getOrgId(),
                req.getTypeIdsList(),req.getSizeNameList(),req.getTypeParentId(),req.getLevelNum(),req.getLevel(),
                req.getColumn(),req.getOrder(),pubOrg.getLevelFlag(),req.getTypeName(),req.getStartTime(),req.getEndTime());
        if (req.getRemoveEmpty()){
            tjOrgCountDtoList.removeIf(tjOrgCountDto -> tjOrgCountDto.getNumber()==0 );
        }
        return tjOrgCountDtoList;
    }



//    @Override
//    public List<TjOrgCountDto> TjOrgCountDetailList(TjOrgCountReq req) {
//        if (ObjectUtil.isNotNull(req.getColumn()) && !req.getColumn().trim().isEmpty() &&
//                (req.getOrder().equalsIgnoreCase("asc")|| req.getOrder().equalsIgnoreCase("desc")) &&
//                ObjectUtil.isNotNull(req.getOrder()) && !req.getOrder().trim().isEmpty()) {
//            req.setColumn(req.getColumn().equals("createTime")
//                    ? null : req.getColumn().replaceAll("[A-Z]", "_$0").toLowerCase());
//            req.setOrder((req.getOrder().equals("desc")||req.getOrder().equals("asc"))
//                    ? req.getOrder().toLowerCase() : null);
//        }
//        List<TjOrgCountDto> returnList=equipmentCountSummaryMapper.TjOrgCountDetail(req.getOrgId(),
//                req.getTypeIdsList(),req.getSizeNameList(),req.getYear(),req.getTypeParentId(),
//                req.getMonthList(),req.getLevelNum(),req.getLevel(),req.getColumn(),req.getOrder(),req.getTypeName());
//        return returnList;
//    }


    @Override
    public List<TjOrgCountDto> TjOrgCountByType(TjOrgCountReq req) {
        return equipmentCountSummaryMapper.TjOrgCountByType(req);
    }

    //首页出入库统计
    @Override
    public List<TjOutAndInDto> TjOutAndInCount(TjOrgCountReq req) {
        List<TjOutAndInDto> returnList=logSummaryMapper.TjOutAndInCount(req);
        return returnList;
    }
    @Override
    public void TjOrgCountExport(TjOrgCountReq req) {
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        List<String> orgList= inventorySummaryMapper.getTotalData(String.valueOf(req.getOrgId()));
        List<TjOrgCountDto> tjOrgCountList=new ArrayList<>();

        if (StringUtils.isNotEmpty(req.getStartTime())){
            req.setStartTime(req.getStartTime()+"-01 00:00:00");
        }
        if (StringUtils.isNotEmpty(req.getEndTime())){
            req.setEndTime(DateTimeUtil.getLastDayOfMonth(req.getEndTime()));
        }
        List<CompletableFuture<TjOrgCountDto>> futures = orgList.stream()
                .map(orgId -> CompletableFuture.supplyAsync(() ->
                        equipmentCountSummaryMapper.TjOrgCount(orgId,
                                req.getTypeIdsList(), req.getSizeNameList(),
                                req.getTypeParentId(), req.getTypeName(), req.getStartTime(), req.getEndTime()))
                )
                .collect(Collectors.toList());
// 等待所有 CompletableFuture 完成
        CompletableFuture<Void> allOf = CompletableFuture.allOf( futures.toArray(new CompletableFuture[0]));


        allOf.join();
        tjOrgCountList = futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());

        if ((!req.getOrgId().equals(JYZBConstant.ORG_ID_PRODUCTION) || !req.getOrgId().equals(JYZBConstant.ORG_ID_TEST))
                && pubOrg.getLevelFlag()!=1){
            TjOrgCountDto OrgDataSelf=equipmentCountSummaryMapper.TjOrgCountSelf(req.getOrgId(),
                    req.getTypeIdsList(),req.getSizeNameList(),req.getTypeParentId(),
                    req.getTypeName(),req.getStartTime(),req.getEndTime());
            OrgDataSelf.setLevel(0);
            OrgDataSelf.setOrgName(OrgDataSelf.getOrgName()+"本级");
            OrgDataSelf.setDName(OrgDataSelf.getDName()+"本级");
            OrgDataSelf=fillingPriceEmptyData(OrgDataSelf);
            TjOrgCountDto OrgData =equipmentCountSummaryMapper.TjOrgCountleve4(req.getOrgId(),
                    req.getTypeIdsList(),req.getSizeNameList(),req.getTypeParentId(),
                    pubOrg.getLevelFlag(),req.getTypeName(),req.getStartTime(),req.getEndTime());
            if (ObjectUtil.isNotNull(OrgData)){

                OrgData.setLevel(1);
                OrgData.setOrgName(OrgData.getOrgName()+"直属下级");
                OrgData.setDName(OrgData.getDName()+"直属下级");
                OrgData=fillingPriceEmptyData(OrgData);
                tjOrgCountList.add(OrgData);
                tjOrgCountList.add(OrgDataSelf);
            }
        }

        //查询出来的组织机构进行判断，如果该组织机构下的装备装备总数为0，那么将该组织机构从list中移除
        if (req.getRemoveEmpty()){
            tjOrgCountList.removeIf(TjOrgCountDto -> TjOrgCountDto.getNumber() == 0 );
        }

        //对组织机构进行排序
        //判断是否有排序规则，如果有排序规则且排序规则不是create_time desc，那么直接按照排序规则进行排序，否则按照默认的组织机构code编码进行排序
        if (ObjectUtil.isNull(req.getColumn())|| (req.getColumn().equals("createTime") && req.getOrder().equals("desc")) ||
                (req.getColumn().equals("createTime") && req.getOrder().equals("asc"))){
            Comparator<TjOrgCountDto> orgComparator = SortingUtil.createOrgComparator();
            Collections.sort(tjOrgCountList, orgComparator);
        }else {
            Comparator<Object> columnOrderComparator = SortingUtil.createColumnOrderComparator(req.getColumn(), req.getOrder());
            Collections.sort(tjOrgCountList, columnOrderComparator);
        }

        //对组织机构进行排序
        Map<String, List<?>> map = new LinkedHashMap<>();
        for (TjOrgCountDto dto: tjOrgCountList) {
            TjOrgCountReq tjOrgCountReq = new TjOrgCountReq();
            BeanPlusUtil.copyProperties(req,tjOrgCountReq);
            if (ObjectUtil.isNotNull(dto.getLevel()) &&(dto.getLevel()==1 || dto.getLevel()==0)){
                dto.setLevelNum(1);
                tjOrgCountReq.setLevelNum(1);
            }else {
                dto.setLevelNum(0);
                tjOrgCountReq.setLevelNum(0);
            }
            tjOrgCountReq.setOrgId(dto.getOrgId());
            List<TjOrgCountDto> tjOrgCountDtoList = TjOrgCountDetail(tjOrgCountReq);
            TjOrgCountDto vo = new TjOrgCountDto();
            BeanPlusUtil.copyProperties(dto,vo);
            vo.setTypeName("合计");
            tjOrgCountDtoList.add(vo);
            List<TjOrgCountExportVo> collect = tjOrgCountDtoList.stream().map(tjOrgCountDto -> {
                TjOrgCountExportVo tjOrgCountExportVo = new TjOrgCountExportVo();
                BeanPlusUtil.copyProperties(tjOrgCountDto, tjOrgCountExportVo);
                return tjOrgCountExportVo;
            }).collect(Collectors.toList());
            map.put(dto.getDName(),collect);// 将要导出的数据列表放入 map 中，其中 "orgName" 是 sheet 的名称
        }

        HttpServletResponse response = HttpServletUtil.getResponse();
        ExcelExportParam excelExportParam = new ExcelExportParam();
        excelExportParam.setResponse(response); // 设置 HttpServletResponse
        excelExportParam.setClazz(TjOrgCountExportVo.class); // 设置实体类的类型
        excelExportParam.setFileName("使用统计报表"); // 设置文件名
        excelExportParam.setExcelTypeEnum(ExcelTypeEnum.XLSX); // 设置 Excel 类型，比如 XLSX 或 XLS
        excelExportParam.setMap(map);
        // 调用方法进行导出
        officeExcelApi.easyExportManySheet(excelExportParam);

    }

    @Override
    public List<Top5Dto> GetTop5(TjOrgCountReq req) {
        int length = req.getFindCode().length();
        return equipmentCountSummaryMapper.GetTop5(req,length);
    }

    @Override
    public List<GroupByCountDto> GetGroupByCount(TjOrgCountReq req) {
        int length = req.getFindCode().length();
        return equipmentCountSummaryMapper.GetGroupByCount(req,length);
    }

    @Override
    public List<InventorySummary> GetCount(TjOrgCountReq req) {
        int length = req.getFindCode().length();
        List<InventorySummary> tjOutAndInDtos=new ArrayList<>();
        if (length<12){

            tjOutAndInDtos = equipmentCountSummaryMapper.GetCount(req, length);
        }else {
            InventorySumReq inventorySumReq=new InventorySumReq();
            PubOrg pubOrg = pubOrgService.PubOrgCodeExist(req.getFindCode());
            inventorySumReq.setOrgId(pubOrg.getOrgId().toString());
            tjOutAndInDtos = inventorySummaryService.getTotalNumberAndPrice(inventorySumReq);
        }
        InventorySummary inventorySummary = tjOutAndInDtos.get(0);
        req.setOrgId(inventorySummary.getOrgId());
        Year now = Year.now();
        int year = now.getValue();
        req.setStartTime(year+"-01");
        req.setEndTime(year+"-12");
        FinalTjOrgCountDto finalTjOrgCountDto = TjOrgCountSum(req);
        inventorySummary.setUseCount(finalTjOrgCountDto.getUseCount());
        inventorySummary.setBrokenCount(finalTjOrgCountDto.getBrokenCount());
        inventorySummary.setFixCount(finalTjOrgCountDto.getFixCount());

        return tjOutAndInDtos;
    }

    @Override
    public AreaTypeDto GetAreaType(TjOrgCountReq req) {
        int length = req.getFindCode().length();
        PubOrg pubOrg=new PubOrg();
        if (length<12){

            List<PubOrg> list = pubOrgService.list(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getFindCode, req.getFindCode())
                    .isNotNull(PubOrg::getLevelFlag)
                    .orderByAsc(PubOrg::getLevelFlag));
            if (CollectionUtil.isNotEmpty(list)){
                pubOrg=list.get(0);
            }
        }else {
            List<PubOrg> list = pubOrgService.list(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgCode, req.getFindCode())
                    .isNotNull(PubOrg::getLevelFlag)
                    .orderByAsc(PubOrg::getLevelFlag));
            if (CollectionUtil.isNotEmpty(list)){
                pubOrg=list.get(0);
            }
        }
        //将九大类查询出来并且存入返回对象中去
        List<String> typeNames = equipmentCountSummaryMapper.getTypeParentName();
        AreaTypeDto areaTypeDto = new AreaTypeDto();
        areaTypeDto.setPList(typeNames);
        TjOrgEqsReq tjOrgEqsReq = new TjOrgEqsReq();
        tjOrgEqsReq.setOrgId(pubOrg.getOrgId());
        tjOrgEqsReq.setSizeNameList(new ArrayList<>());
        tjOrgEqsReq.setTypeIdsList(new ArrayList<>());
        List<TjOrgEqsDto> eqsDtoList = GetTjDataList(tjOrgEqsReq);
        //将九大类汇总数据放入
        for (TjOrgEqsDto dto:eqsDtoList) {
            List<AreaChildrenDto> childrenDtoList=equipmentCountSummaryMapper.getChildren(dto,pubOrg.getLevelFlag());
            dto.setChildren(childrenDtoList);
        }
        areaTypeDto.setData(eqsDtoList);
        return areaTypeDto;
    }


    @Override
    public SyWxBfDto GetSyWxBf(TjOrgCountReq req) {
        SyWxBfDto syWxBfDto = new SyWxBfDto();
        int length = req.getFindCode().length();
        List<List<Integer>> reList=new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            List<Integer> list=equipmentCountSummaryMapper.GetSyWxBf(req,length,i);
            reList.add(list);
        }
        syWxBfDto.setDataType(reList);
        List<String> typeNames = equipmentCountSummaryMapper.getTypeParentName();
        syWxBfDto.setPList(typeNames);
        return syWxBfDto;
    }

    @Override
    public TjOrgDto GetPageOrgTj(TjOrgCountReq req) {
        TjOrgDto tjOrgDto = equipmentCountSummaryMapper.GetPageOrgTj(req);
        List<ContentDto> contentDtoList=equipmentCountSummaryMapper.getBydetail(req);
        tjOrgDto.setContent(contentDtoList);
        for (ContentDto dto:contentDtoList) {
            List<ContentChildrenDto> childrenDtos=equipmentCountSummaryMapper.getByChildren(dto);
            dto.setChildren(childrenDtos);
        }
        return tjOrgDto;
    }

    @Override
    public List<PubOrg> GetOrgJWDByCode(TjOrgCountReq req) {
        return  pubOrgService.list(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getDelFlag,1).eq(PubOrg::getFindCode,req.getFindCode()));

    }

    @Override
    public List<InventorySummary> GetNameList(TjOrgCountReq req) {
        PubOrg one = pubOrgService.getOne(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgCode, req.getOrgCode()));
        InventorySumReq sumReq = new InventorySumReq();
        sumReq.setOrgId(one.getOrgId().toString());
        sumReq.setColumn("create_time");
        return inventorySummaryMapper.GetEquipmentSummary(sumReq,null,null);
    }
// ---------------------------------------  装备维度的报表数据   ------------------------------
    @Override
    public PageResult<TjEqsSumDto> TjEqsSumByOrg(TjEqsSumReq req) {
        if (ObjectUtil.isNotNull(req.getColumn()) && !req.getColumn().trim().isEmpty() &&
                (req.getOrder().equalsIgnoreCase("asc")|| req.getOrder().equalsIgnoreCase("desc")) &&
                ObjectUtil.isNotNull(req.getOrder()) && !req.getOrder().trim().isEmpty()) {
            //修改字段，和数据库字段进行统一
            req.setColumn(req.getColumn().equals("createTime")
                    ? null : req.getColumn().replaceAll("[A-Z]", "_$0").toLowerCase());
            req.setOrder((req.getOrder().equals("desc")||req.getOrder().equals("asc"))
                    ? req.getOrder().toLowerCase() :null );
        }
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        int size=inventorySummaryMapper.getEqsSumByOrgSum(req);
        System.out.println("req.getPageSize() = " + req.getPageSize());
        System.out.println("req.getPageNo() = " + req.getPageNo());

        List<TjEqsSumDto> list=inventorySummaryMapper.getEqsSumByOrg(req,(req.getPageNo()-1)*req.getPageSize(),req.getPageSize());
        Page<TjEqsSumDto> page = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        page.setRecords(list);
        page.setTotal(size);
        return PageResultFactory.createPageResult(page);
    }

    @Override
    public List<TjEqsSumDto> TjEqsSumByOrgDetail(TjEqsSumReq req) {

        return inventorySummaryMapper.TJEqsSumByOrgDetail(req);
    }

    @Override
    public FinalTjRqsSumDto TjEqsSumByOrgSum(TjEqsSumReq req) {
        FinalTjRqsSumDto finalTjRqsSumDto = inventorySummaryMapper.TjEqsSumByOrgSum(req);

        return ObjectUtil.isNull(finalTjRqsSumDto)?new FinalTjRqsSumDto():finalTjRqsSumDto;
    }


    @Override
    public PageResult<OrderMain> TjEqsSumByOrder(OrderMainReq req) {
        Page<OrderMain> page= PageFactory.getDefaultPage(req.getPageNo(),req.getPageSize());
        List<OrderMain> list=orderMainMapper.TjEqsSumByOrder(req,(req.getPageNo()-1)*req.getPageSize(),req.getPageSize());
        int size =orderMainMapper.TjEqsSumByOrderCount(req);
        page.setTotal(size);
        page.setRecords(list);
        return PageResultFactory.createPageResult(page);
    }

    @Override
    public PageResult<BusForm> TjEqsSumByBusForm(QueryBusFormReq req) {
        Page<BusForm> page= PageFactory.getDefaultPage(req.getPageNo(),req.getPageSize());
        List<BusForm> list=busFormMapper.TjEqsSumByBusForm(req,(req.getPageNo()-1)*req.getPageSize(),req.getPageSize());
        int size =busFormMapper.TjEqsSumByBusFormCount(req);
        page.setTotal(size);
        page.setRecords(list);
        return PageResultFactory.createPageResult(page);
    }



    //-------------------------------------------人员统计报表----------------------------------------------------------
    @Override
    public PageResult<TjOrgPoliceDto> TjOrgPolice(TjOrgPoliceReq req) {
        int size=policeEquipmentMapper.getCount(req);
        if (ObjectUtil.isNull(req.getPageNo()) && ObjectUtil.isNull(req.getPageSize())) {
            req.setPageNo(1L);
            req.setPageSize(10L);
        }
        List<TjOrgPoliceDto> list= policeEquipmentMapper.TjOrgPolice(req,(req.getPageNo()-1)* req.getPageSize(),req.getPageSize());
        Page<TjOrgPoliceDto> page = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        page.setTotal(size);
        page.setRecords(list);
        return PageResultFactory.createPageResult(page);
    }

    @Override
    public FinalTjOrgPoliceDto TjOrgPoliceSum(TjOrgPoliceReq req) {
        FinalTjOrgPoliceDto finalTjOrgPoliceDto=policeEquipmentMapper.TjOrgPoliceSum(req);
        if (ObjectUtil.isNotNull(finalTjOrgPoliceDto)){
            return finalTjOrgPoliceDto;
        }else {
            return new FinalTjOrgPoliceDto();
        }
    }

//    @Override
//    public PageResult<TjOrgPoliceDto> TjOrgPoliceDetailPage(TjOrgPoliceReq req) {
//        if (ObjectUtil.isNull(req.getPageNo()) && ObjectUtil.isNull(req.getPageSize())) {
//            req.setPageNo(1L);
//            req.setPageSize(10L);
//        }
//        int size = policeEquipmentMapper.TjOrgPoliceDetailSum(req);
//        List<TjOrgPoliceDto> returnList=policeEquipmentMapper.TjOrgPoliceDetail(req,(req.getPageNo()-1)* req.getPageSize(),req.getPageSize());
//        Page<TjOrgPoliceDto> page = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
//        page.setTotal(size);
//        page.setRecords(returnList);
//        return PageResultFactory.createPageResult(page);
//    }

    @Override
    public List<TjOrgPoliceDto> TjOrgPoliceDetailList(TjOrgPoliceReq req) {
        List<TjOrgPoliceDto> returnList=policeEquipmentMapper.TjOrgPoliceDetail(req,null,null);
        return returnList;
    }

    @Override
    public void TjOrgPoliceExport(TjOrgPoliceReq req) {
        List<TjOrgPoliceDto> list= policeEquipmentMapper.TjOrgPolice(req,null,null);
        Map<String, List<?>> map = new LinkedHashMap<>();
        for (TjOrgPoliceDto dto: list) {
            req.setPoliceId(dto.getPoliceId());
            List<TjOrgPoliceDto> tjOrgPoliceDtos = TjOrgPoliceDetailList(req);

            List<TjOrgPoliceExportVo> collect = tjOrgPoliceDtos.stream().map(tjOrgPoliceDto -> {
                TjOrgPoliceExportVo tjOrgPoliceExportVo = new TjOrgPoliceExportVo();
                BeanPlusUtil.copyProperties(tjOrgPoliceDto, tjOrgPoliceExportVo);
                return tjOrgPoliceExportVo;
            }).collect(Collectors.toList());
            map.put(dto.getPoliceName(),collect);// 将要导出的数据列表放入 map 中，其中 "policeName" 是 sheet 的名称
        }

        HttpServletResponse response = HttpServletUtil.getResponse();
        ExcelExportParam excelExportParam = new ExcelExportParam();
        excelExportParam.setResponse(response); // 设置 HttpServletResponse
        excelExportParam.setClazz(TjOrgPoliceExportVo.class); // 设置实体类的类型
        excelExportParam.setFileName("人员统计报表"); // 设置文件名
        excelExportParam.setExcelTypeEnum(ExcelTypeEnum.XLSX); // 设置 Excel 类型，比如 XLSX 或 XLS
        excelExportParam.setMap(map);
        // 调用方法进行导出
        officeExcelApi.easyExportManySheet(excelExportParam);
    }



}
