package com.junmp.jyzb.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.junmp.jyzb.api.bean.dto.EqsSumDto;
import com.junmp.jyzb.api.bean.dto.InventorySumDto;
import com.junmp.jyzb.api.bean.dto.TjDto.*;
import com.junmp.jyzb.api.bean.query.InventoryReq;
import com.junmp.jyzb.api.bean.query.TjReq.TjOrgCountReq;
import com.junmp.jyzb.api.bean.query.TjReq.TjOrgEqsReq;
import com.junmp.jyzb.api.bean.query.TjReq.TjOrgPoliceReq;
import com.junmp.jyzb.api.bean.query.TjReq.TjOrgPriceReq;
import com.junmp.jyzb.api.bean.vo.*;
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.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.apache.poi.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
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 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<>();

        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());
                }))
                .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()!=1369509498032808905L)
        {
            TjOrgEqsDto OrgDataSelf=inventorySummaryMapper.GetInvSelfSum(String.valueOf(req.getOrgId()),
                req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                req.getSizeNameList().isEmpty() ? null : req.getSizesAsString());
            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());
            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);
        }

        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 = createOrgComparator();
            Collections.sort(allData, orgComparator);
        }else {
            Comparator<Object> columnOrderComparator = 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 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);
        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());
                }))
                .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()!=1369509498032808905L)
        {
            TjOrgEqsDto OrgDataSelf=inventorySummaryMapper.GetInvSelfSum(String.valueOf(req.getOrgId()),
                    req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                    req.getSizeNameList().isEmpty() ? null : req.getSizesAsString());
            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());
            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());
        }
        return finalTjOrgEqsDto;
    }



    //    @Override
    public List<TjOrgEqsDto> GetTjDataDetail(TjOrgEqsReq 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"))
                    ? null : req.getOrder().toLowerCase());
        }

        List<TjOrgEqsDto> allData=inventorySummaryMapper.getTotalDataDetail(String.valueOf(req.getOrgId()),req.getTypeIdsList(),req.getSizeNameList(),req.getLevelNum(),req.getLevel(),req.getColumn(),req.getOrder());


        if (req.getRemoveEmpty())//如果需要删除数据为0的话，前端传true，否则保留数据为0
        {
            allData.removeIf(tjOrgEqsDto -> tjOrgEqsDto.getTotalNumber() == 0);
        }
        //将组织机构进行排序后再进行返回
        if (req.getColumn()==null){
            Comparator<TjOrgEqsDto> orgComparator = 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());
                }))
                .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()!=1369509498032808905L)
        {
            TjOrgEqsDto OrgDataSelf=inventorySummaryMapper.GetInvSelfSum(String.valueOf(req.getOrgId()),
                    req.getTypeIdsList().isEmpty() ? null : req.getTypeIdsAsString(),
                    req.getSizeNameList().isEmpty() ? null : req.getSizesAsString());
            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());
            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 = createOrgComparator();
        Collections.sort(allData, orgComparator);
        for (TjOrgEqsDto tjOrgEqsDto:allData) {
            if (tjOrgEqsDto.getLevel()==1 || tjOrgEqsDto.getLevel()==0){
                tjOrgEqsDto.setLevelNum(1);
            }else {
                tjOrgEqsDto.setLevelNum(0);
            }
            TjOrgEqsReq tjOrgEqsReq = new TjOrgEqsReq();
            BeanPlusUtil.copyProperties(tjOrgEqsDto,tjOrgEqsReq);
            tjOrgEqsReq.setColumn(req.getColumn());
            tjOrgEqsReq.setOrder(req.getOrder());
            List<TjOrgEqsDto> tjOrgEqsDtos = GetTjDataDetail(tjOrgEqsReq);
            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 中，其中 "orgName" 是 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"))
                ? null : req.getOrder().toLowerCase());
        List<InventorySumDto> returnList=inventorySummaryMapper.TjOrgEqsDetail(req.getOrgId(),req.getTypeIdsList(),
                req.getSizeNameList(),req.getColumn(),req.getOrder());
        return returnList;
    }

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


    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() )
                ))
                .collect(Collectors.toList());
// 等待所有 CompletableFuture 完成
        CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
//
        // 等待所有 CompletableFuture 完成
        allOf.join();


        if (req.getOrgId()!=1369509498032808905L){
            //获取本级数据
            TjOrgPriceDto OrgDataSelf=priceSumSummaryMapper.TjOrgPriceBySelf(req.getOrgId(), req.getYear(),req.getTypeIdsList(),
                    req.getSizeNameList());
            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());
            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 = createOrgComparator();
            Collections.sort(tjOrgPriceDtoList, orgComparator);
        }else {
            Comparator<Object> columnOrderComparator = 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<CompletableFuture<TjOrgPriceDto>> futures = orgList.stream()
                .map(orgId -> CompletableFuture.supplyAsync(() ->
                        priceSumSummaryMapper.TjOrgPrice(orgId, req.getYear(),req.getTypeIdsList(),req.getSizeNameList() )
                ))
                .collect(Collectors.toList());

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

        List<TjOrgPriceDto> tjOrgPriceDtoList = orgList.parallelStream()
                .map(orgId -> CompletableFuture.supplyAsync(() ->
                        priceSumSummaryMapper.TjOrgPrice(orgId, req.getYear(), req.getTypeIdsList(), req.getSizeNameList())))
                .map(CompletableFuture::join)
                .collect(Collectors.toList());

        if (req.getOrgId()!=1369509498032808905L){
            //获取本级数据
            TjOrgPriceDto OrgDataSelf=priceSumSummaryMapper.TjOrgPriceBySelf(req.getOrgId(), req.getYear(),req.getTypeIdsList(),
                    req.getSizeNameList());
            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());
            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()+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> TjOrgPriceDetail1(TjOrgPriceReq 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"))
                    ? null : req.getOrder().toLowerCase());
        }
        List<TjOrgPriceDto> allData=priceSumSummaryMapper.getTotalPriceDetail(req.getOrgId(), req.getYear(),
                req.getTypeIdsList(),req.getSizeNameList(),req.getLevelNum(),req.getLevel(),req.getColumn(),req.getOrder());
        if (req.getRemoveEmpty()){
            allData.removeIf(tjOrgEqsDto -> tjOrgEqsDto.getStartNum() == 0 && tjOrgEqsDto.getEndNum() == 0
                    && tjOrgEqsDto.getDestoryNum()==0);
        }
        if (req.getColumn()==null){
            //将组织机构进行排序后再进行返回
            Comparator<TjOrgPriceDto> orgComparator = createOrgComparator();
            Collections.sort(allData, orgComparator);
        }

        return allData;
    }


    @Override
    public List<TjOrgPriceDto> TjOrgPriceDetailList(TjOrgPriceReq req) {
        //先拿到符合条件的组织机构，再遍历组织机构组成数据
//(如果传其他不是数据库字段参数或者排序规则不是deac或者asc可能会出现错误)
        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"))
                    ? null : req.getOrder().toLowerCase());
        }
        List<TjOrgPriceDto> returnList=priceSumSummaryMapper.TjOrgPriceDetail(req.getOrgId(),req.getYear(),
                req.getTypeIdsList(),req.getSizeNameList(), req.getColumn(), req.getOrder());
        return returnList;
    }


    @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() )
                ))
                .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()!=1369509498032808905L){
            //获取本级数据
            TjOrgPriceDto OrgDataSelf=priceSumSummaryMapper.TjOrgPriceBySelf(req.getOrgId(), req.getYear(),req.getTypeIdsList(),
                    req.getSizeNameList());
            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());
            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);
        }

        //对组织机构进行排序
        Map<String, List<?>> map = new LinkedHashMap<>();
        Comparator<TjOrgPriceDto> orgComparator = createOrgComparator();
        Collections.sort(tjOrgPriceDtoList, orgComparator);
        for (TjOrgPriceDto dto: tjOrgPriceDtoList) {
            TjOrgPriceReq tjOrgPriceReq = new TjOrgPriceReq();
            if (req.getLevel()!=null){
                dto.setLevelNum(1);
            }else {
                dto.setLevelNum(0);
            }
            BeanPlusUtil.copyProperties(dto,tjOrgPriceReq);
            tjOrgPriceReq.setRemoveEmpty(req.getRemoveEmpty());
            tjOrgPriceReq.setYear(req.getYear());
            List<TjOrgPriceDto> tjOrgPriceDtos = TjOrgPriceDetail(tjOrgPriceReq);
            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<>();

        List<CompletableFuture<TjOrgCountDto>> futures = orgList.stream()
                .map(orgId -> CompletableFuture.supplyAsync(() ->
                        equipmentCountSummaryMapper.TjOrgCount(orgId,
                                req.getTypeIdsList(), req.getSizeNameList(),
                                req.getYear(), req.getTypeParentId(), req.getMonthList()))
                )
                .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()!=1369509498032808905L){
            TjOrgCountDto OrgDataSelf=equipmentCountSummaryMapper.TjOrgCountSelf(req.getOrgId(),
                    req.getTypeIdsList(),req.getSizeNameList(),req.getYear(),req.getTypeParentId(),
                    req.getMonthList());
            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.getYear(),req.getTypeParentId(),
                    req.getMonthList(),pubOrg.getLevelFlag());
            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 = createOrgComparator();
            Collections.sort(tjOrgCountList, orgComparator);
        }else {
            Comparator<Object> columnOrderComparator = 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());
        orgData.setFixCount(ObjectUtil.isNull(orgData.getFixCount()) ? 0 : orgData.getFixCount());
        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<>();

        List<CompletableFuture<TjOrgCountDto>> futures = orgList.stream()
                .map(orgId -> CompletableFuture.supplyAsync(() ->
                        equipmentCountSummaryMapper.TjOrgCount(orgId,
                                req.getTypeIdsList(), req.getSizeNameList(),
                                req.getYear(), req.getTypeParentId(), req.getMonthList()))
                )
                .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()!=1369509498032808905L){
            TjOrgCountDto OrgDataSelf=equipmentCountSummaryMapper.TjOrgCountSelf(req.getOrgId(),
                    req.getTypeIdsList(),req.getSizeNameList(),req.getYear(),req.getTypeParentId(),
                    req.getMonthList());
            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.getYear(),req.getTypeParentId(),
                    req.getMonthList(),pubOrg.getLevelFlag());
            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.setFixCount(ObjectUtil.isNull(tj.getFixCount())?0: tj.getFixCount());
            tj.setUseCount(ObjectUtil.isNull(tj.getUseCount())?0: tj.getUseCount());
            tj.setNumber(ObjectUtil.isNull(tj.getNumber())?0: tj.getNumber());
            finalTjOrgCountDto.setFixCount(finalTjOrgCountDto.getFixCount()+tj.getFixCount());
            finalTjOrgCountDto.setUseCount(finalTjOrgCountDto.getUseCount()+ tj.getUseCount());
            finalTjOrgCountDto.setNumber(finalTjOrgCountDto.getNumber()+ tj.getNumber());
        }
        return finalTjOrgCountDto;
    }

    @Override
    public List<TjOrgCountDto> TjOrgCountDetail(TjOrgCountReq req) {
        if ((req.getColumn().equals("createTime") && req.getOrder().equals("desc"))||(req.getColumn().equals("createTime") && req.getOrder().equals("asc"))){
            req.setColumn(null);
            req.setOrder(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());
        }
        List<TjOrgCountDto> tjOrgCountDtoList=equipmentCountSummaryMapper.TjOrgCountTotalNum(req.getOrgId(),
                req.getTypeIdsList(),req.getSizeNameList(),req.getYear(),req.getTypeParentId(),
                req.getMonthList(),req.getLevelNum(),req.getLevel(),req.getColumn(),req.getOrder());
        if (req.getRemoveEmpty()){
            tjOrgCountDtoList.removeIf(tjOrgCountDto -> tjOrgCountDto.getNumber()==0 );
        }
        return tjOrgCountDtoList;
    }

    @Override
    public List<TjOrgCountDto> TjOrgCountDetail1(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"))
                    ? null : req.getOrder().toLowerCase());
        }

        List<TjOrgCountDto> tjOrgCountDtoList=equipmentCountSummaryMapper.TjOrgCountTotalDetail(req.getOrgId(),
                req.getTypeIdsList(),req.getSizeNameList(),req.getYear(),req.getTypeParentId(),
                req.getMonthList(),req.getLevelNum(),req.getLevel(),req.getColumn(),req.getOrder());
        if (req.getRemoveEmpty()){
            tjOrgCountDtoList.removeIf(tjOrgCountDto -> tjOrgCountDto.getNumber()==0 );
        }
        if (req.getColumn()==null){
            //将组织机构进行排序后再进行返回
            Comparator<TjOrgCountDto> orgComparator = createOrgComparator();
            Collections.sort(tjOrgCountDtoList, orgComparator);
        }
        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"))
                    ? null : req.getOrder().toLowerCase());
        }
        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());
        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<>();

        List<CompletableFuture<TjOrgCountDto>> futures = orgList.stream()
                .map(orgId -> CompletableFuture.supplyAsync(() ->
                        equipmentCountSummaryMapper.TjOrgCount(orgId,
                                req.getTypeIdsList(), req.getSizeNameList(),
                                req.getYear(), req.getTypeParentId(), req.getMonthList()))
                )
                .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()!=1369509498032808905L){
            TjOrgCountDto OrgDataSelf=equipmentCountSummaryMapper.TjOrgCountSelf(req.getOrgId(),
                    req.getTypeIdsList(),req.getSizeNameList(),req.getYear(),req.getTypeParentId(),
                    req.getMonthList());
            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.getYear(),req.getTypeParentId(),
                    req.getMonthList(),pubOrg.getLevelFlag());
            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 = createOrgComparator();
            Collections.sort(tjOrgCountList, orgComparator);
        }else {
            Comparator<Object> columnOrderComparator = createColumnOrderComparator(req.getColumn(), req.getOrder());
            Collections.sort(tjOrgCountList, columnOrderComparator);
        }

        //对组织机构进行排序
        Map<String, List<?>> map = new LinkedHashMap<>();
        for (TjOrgCountDto dto: tjOrgCountList) {
            TjOrgCountReq tjOrgCountReq = new TjOrgCountReq();
            if (req.getLevel()!=null){
                dto.setLevelNum(1);
            }else {
                dto.setLevelNum(0);
            }
            BeanPlusUtil.copyProperties(dto,tjOrgCountReq);
            tjOrgCountReq.setRemoveEmpty(req.getRemoveEmpty());
            tjOrgCountReq.setYear(req.getYear());
            List<TjOrgCountDto> tjOrgCountDtoList = TjOrgCountDetail(req);
            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 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);
    }




//-----------------------------------------------排序规则方法-------------------------------------------------

    //自定义排序
    public <T> Comparator<T> createColumnOrderComparator(String column,String order) {
        return (object1, object2) -> {
            try {
                Field field = object1.getClass().getDeclaredField(column);
                field.setAccessible(true);
                Object fieldValue1 = field.get(object1);
                Object fieldValue2 = field.get(object2);

                if (fieldValue1 instanceof Comparable && fieldValue2 instanceof Comparable) {
                    int result = ((Comparable) fieldValue1).compareTo(fieldValue2);
                    return order.equalsIgnoreCase("desc") ? -result : result;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 0;
        };
    }


    //组织机构排序
    public <T> Comparator<T> createOrgComparator() {
        return (org1,org2) ->{

            try {
                String orgCode1 = (String) org1.getClass().getMethod("getOrgCode").invoke(org1);
                String orgCode2 = (String) org2.getClass().getMethod("getOrgCode").invoke(org2);

                // 判断是否包含字母
                boolean hasLetter1 = orgCode1.matches(".*[a-zA-Z]+.*");
                boolean hasLetter2 = orgCode2.matches(".*[a-zA-Z]+.*");

                // 如果其中一个包含字母，则将其放到排序的最后
                if (hasLetter1 && !hasLetter2) {
                    return 1; // orgCode1包含字母，orgCode2不包含字母，orgCode1排在orgCode2后面
                } else if (!hasLetter1 && hasLetter2) {
                    return -1; // orgCode1不包含字母，orgCode2包含字母，orgCode1排在orgCode2前面
                }

                // 如果两个orgCode都不含有字母，则按照每两位进行排序
                String[] orgCodeArray1 = orgCode1.split("(?<=\\G..)");
                String[] orgCodeArray2 = orgCode2.split("(?<=\\G..)");

                // 从最后一组（即最后两位）开始比较数字大小
                int index1 = orgCodeArray1.length - 1;
                int index2 = orgCodeArray2.length - 1;
                while (index1 >= 0 && index2 >= 0) {
                    String codeValue1 = orgCodeArray1[index1];
                    String codeValue2 = orgCodeArray2[index2];

                    // 判断是否可以转换为整数，如果不能，则说明包含字母，直接返回结果
                    try {
                        int intValue1 = Integer.parseInt(codeValue1, 10);
                        int intValue2 = Integer.parseInt(codeValue2, 10);
                        int compareResult = Integer.compare(intValue1, intValue2);
                        if (compareResult != 0) {
                            return compareResult;
                        }
                    } catch (NumberFormatException e) {
                        // orgCode包含字母，直接返回结果
                        return codeValue1.compareTo(codeValue2);
                    }

                    index1--;
                    index2--;
                }

                // 在数字比较的基础上，再根据level进行排序
                Integer level1 = (Integer) org1.getClass().getMethod("getLevel").invoke(org1);
                Integer level2 = (Integer) org2.getClass().getMethod("getLevel").invoke(org2);
                return Integer.compare(level1, level2);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        };
    }


}
