package com.bonus.material.basic.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.bonus.common.biz.enums.MaTypeManageTypeEnum;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.basic.domain.*;
import com.bonus.material.basic.domain.vo.MaTypeSelectInfo;
import com.bonus.material.basic.mapper.ComplexQueryMapper;
import com.bonus.material.basic.service.ComplexQueryService;
import com.bonus.material.ma.domain.Type;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 综合查询服务实现类
 *
 * @Author ma_sh
 * @create 2024/12/16 10:53
 */
@Service
@Slf4j
public class ComplexQueryServiceImpl implements ComplexQueryService {

    @Resource
    private ComplexQueryMapper complexQueryMapper;

    /**
     * 工程机具使用列表
     *
     * @param bean
     * @return
     */
    @Override
    public List<ProjUsingRecord> getProjUsingRecordList(ProjUsingRecord bean) {
        List<ProjUsingRecord> list = new ArrayList<>();
        if (StringUtils.isNotBlank(bean.getExternalIds())) {
            String[] externalIds = bean.getExternalIds().split(",");
            for (String externalId : externalIds) {
                bean.setExternalId(externalId);
                List<ProjUsingRecord> projUsingRecordList = complexQueryMapper.getProjUsingRecordList(bean);
                list.addAll(projUsingRecordList);
            }
        } else {
            list = complexQueryMapper.getProjUsingRecordList(bean);
        }
        return list;
    }

    /**
     * 设备使用追溯查询
     *
     * @param bean
     * @return
     */
    @Override
    public List<MachineHistoryRecordBean> getMachineHistoryRecordList(MachineHistoryRecordBean bean) {
        return complexQueryMapper.getMachineHistoryRecordList(bean);
    }

    /**
     * 导出工程机具使用列表
     *
     * @param bean
     */
    @Override
    public List<ProjUsingRecord> exportProjUsingRecord(ProjUsingRecord bean) {
        // 使用 BigDecimal 常量初始化
        BigDecimal totalLeaseNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalBackNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalUsNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalUsPrice = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        BigDecimal totalTotalPrice = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        List<ProjUsingRecord> list = complexQueryMapper.getProjUsingRecordList(bean);
        if (CollectionUtils.isNotEmpty(list)) {
            ProjUsingRecord projUsingRecord = new ProjUsingRecord();
            for (ProjUsingRecord record : list) {
                totalLeaseNum = totalLeaseNum.add(record.getLeaseNum());
                totalBackNum = totalBackNum.add(record.getBackNum());
                totalUsNum = totalUsNum.add(record.getUsNum());
                totalUsPrice = totalUsPrice.add(record.getUsPrice());
                totalTotalPrice = totalTotalPrice.add(record.getTotalPrice());
            }
            // 设置 ProjUsingDto 总结数据
            projUsingRecord.setLeaseNum(totalLeaseNum.setScale(3, RoundingMode.HALF_UP));
            projUsingRecord.setBackNum(totalBackNum.setScale(3, RoundingMode.HALF_UP));
            projUsingRecord.setUsNum(totalUsNum.setScale(3, RoundingMode.HALF_UP));
            projUsingRecord.setUsPrice(totalUsPrice.setScale(2, RoundingMode.HALF_UP));
            projUsingRecord.setTotalPrice(totalTotalPrice.setScale(2, RoundingMode.HALF_UP));
            projUsingRecord.setUnit("合计");
            list.add(0, projUsingRecord);
        }
        return list;
    }

    /**
     * 机具入库查询列表
     *
     * @param bean
     * @return
     */
    @Override
    public List<InputRecordInfo> getInputRecordList(InputRecordInfo bean) {
        List<InputRecordInfo> recordList = complexQueryMapper.getInputRecordList(bean);
        List<InputRecordInfo> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(recordList)) {
            for (InputRecordInfo inputRecordInfo : recordList) {
                if (StringUtils.isNotBlank(inputRecordInfo.getMaCode())) {
                    String[] split = inputRecordInfo.getMaCode().split(",");
                    if (split.length > 1) {
                        for (String code : split) {
                            InputRecordInfo newRecord = new InputRecordInfo();
                            BeanUtils.copyProperties(inputRecordInfo, newRecord);
                            newRecord.setMaCode(code);
                            newRecord.setInputNum(BigDecimal.ONE);
                            list.add(newRecord);
                        }
                    } else {
                        list.add(inputRecordInfo);
                    }
                } else {
                    list.add(inputRecordInfo);
                }
            }
        }
        if (StringUtils.isNotBlank(bean.getKeyWord())) {
            String keyword = bean.getKeyWord();
            return list.stream().filter(item -> {
                return (StringUtils.isNotBlank(item.getMaCode()) && item.getMaCode().contains(keyword)) ||
                        (StringUtils.isNotBlank(item.getTypeName()) && item.getTypeName().contains(keyword)) ||
                        (StringUtils.isNotBlank(item.getTypeModelName()) && item.getTypeModelName().contains(keyword)) ||
                        (StringUtils.isNotBlank(item.getInputUser()) && item.getInputUser().contains(keyword)) ||
                        (StringUtils.isNotBlank(item.getInputCode()) && item.getInputCode().contains(keyword));
            }).collect(Collectors.toList());
        }
        return list;
    }

    /**
     * 机具出库查询列表
     *
     * @param bean
     * @return
     */
    @Override
    public List<OutRecordInfo> getOutRecordList(OutRecordInfo bean) {
        List<OutRecordInfo> recordList = complexQueryMapper.getOutRecordList(bean);
        List<OutRecordInfo> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(recordList)) {
            for (OutRecordInfo outRecordInfo : recordList) {
                if (StringUtils.isNotBlank(outRecordInfo.getMaCode())) {
                    String[] split = outRecordInfo.getMaCode().split(",");
                    if (split.length > 1) {
                        for (String code : split) {
                            OutRecordInfo recordInfo = new OutRecordInfo();
                            BeanUtils.copyProperties(outRecordInfo, recordInfo);
                            recordInfo.setMaCode(code);
                            recordInfo.setOutNum(BigDecimal.ONE);
                            list.add(recordInfo);
                        }
                    } else {
                        list.add(outRecordInfo);
                    }
                } else {
                    list.add(outRecordInfo);
                }
            }
        }
        return list;
    }

    /**
     * 保有设备总量查询
     *
     * @param bean
     * @return
     */
    @Override
    public List<RetainedEquipmentInfo> getRetainedEquipmentList(RetainedEquipmentInfo bean) {
        BigDecimal totalPrice = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        BigDecimal totalStoreNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalUsNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalDsNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalRepairNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalRepairAuditNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalInputNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalRepairInputNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalPendingScrapNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalScrapNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal totalAllNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        /*BigDecimal fiveReplacementNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal tenReplacementNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        BigDecimal tenPlusReplacementNum = BigDecimal.ZERO.setScale(3, RoundingMode.HALF_UP);
        String fiveReplacementRate = "0%";
        String tenReplacementRate = "0%";
        String tenPlusReplacementRate = "0%";*/
        List<RetainedEquipmentInfo> recordList = complexQueryMapper.getRetainedEquipmentList(bean);
        if (CollectionUtils.isNotEmpty(recordList)) {
            for (RetainedEquipmentInfo retainedEquipmentInfo : recordList) {
                totalStoreNum = totalStoreNum.add(retainedEquipmentInfo.getStoreNum());
                totalUsNum = totalUsNum.add(retainedEquipmentInfo.getUsNum());
                totalDsNum = totalDsNum.add(retainedEquipmentInfo.getDsNum());
                totalRepairNum = totalRepairNum.add(retainedEquipmentInfo.getRepairNum());
                totalRepairAuditNum = totalRepairAuditNum.add(retainedEquipmentInfo.getRepairAuditNum());
                totalInputNum = totalInputNum.add(retainedEquipmentInfo.getInputNum());
                totalRepairInputNum = totalRepairInputNum.add(retainedEquipmentInfo.getRepairInputNum());
                totalPendingScrapNum = totalPendingScrapNum.add(retainedEquipmentInfo.getPendingScrapNum());
                totalScrapNum = totalScrapNum.add(retainedEquipmentInfo.getScrapNum());
                totalAllNum = totalAllNum.add(retainedEquipmentInfo.getAllNum());
                /*fiveReplacementNum = fiveReplacementNum.add(retainedEquipmentInfo.getFiveReplacementNum());
                tenReplacementNum = tenReplacementNum.add(retainedEquipmentInfo.getTenReplacementNum());
                tenPlusReplacementNum = tenPlusReplacementNum.add(retainedEquipmentInfo.getTenPlusReplacementNum());*/
                BigDecimal equipmentPrice = retainedEquipmentInfo.getAllNum()
                        .multiply(retainedEquipmentInfo.getBuyPrice())
                        .divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP);
                totalPrice = totalPrice.add(equipmentPrice);
                BigDecimal allNum = retainedEquipmentInfo.getAllNum();
                /*if (allNum.compareTo(BigDecimal.ZERO) == 0) {
                    fiveReplacementRate = "0%";
                    tenReplacementRate = "0%";
                    tenPlusReplacementRate = "0%";
                } else {
                    fiveReplacementRate = retainedEquipmentInfo.getFiveReplacementNum()
                            .divide(allNum, 4, RoundingMode.HALF_DOWN)
                            .multiply(new BigDecimal(100))
                            .setScale(2, RoundingMode.HALF_UP) + "%";
                    tenReplacementRate = retainedEquipmentInfo.getTenReplacementNum()
                            .divide(allNum, 4, RoundingMode.HALF_DOWN)
                            .multiply(new BigDecimal(100))
                            .setScale(2, RoundingMode.HALF_UP) + "%";
                    tenPlusReplacementRate = retainedEquipmentInfo.getTenPlusReplacementNum()
                            .divide(allNum, 4, RoundingMode.HALF_DOWN)
                            .multiply(new BigDecimal(100))
                            .setScale(2, RoundingMode.HALF_UP) + "%";
                }*/
                retainedEquipmentInfo.setTotalPrice(equipmentPrice);
                /*retainedEquipmentInfo.setFiveReplacementRate(fiveReplacementRate);
                retainedEquipmentInfo.setTenReplacementRate(tenReplacementRate);
                retainedEquipmentInfo.setTenPlusReplacementRate(tenPlusReplacementRate);*/
            }
            /*if (totalAllNum.compareTo(BigDecimal.ZERO) == 0) {
                fiveReplacementRate = "0%";
                tenReplacementRate = "0%";
                tenPlusReplacementRate = "0%";
            } else {
                fiveReplacementRate = fiveReplacementNum
                        .divide(totalAllNum, 4, RoundingMode.HALF_DOWN)
                        .multiply(new BigDecimal(100))
                        .setScale(2, RoundingMode.HALF_UP) + "%";
                tenReplacementRate = tenReplacementNum
                        .divide(totalAllNum, 4, RoundingMode.HALF_DOWN)
                        .multiply(new BigDecimal(100))
                        .setScale(2, RoundingMode.HALF_UP) + "%";
                tenPlusReplacementRate = tenPlusReplacementNum
                        .divide(totalAllNum, 4, RoundingMode.HALF_DOWN)
                        .multiply(new BigDecimal(100))
                        .setScale(2, RoundingMode.HALF_UP) + "%";
            }*/
            if (bean.getIsExport() == 0) {
                RetainedEquipmentInfo retainedEquipmentInfo = new RetainedEquipmentInfo();
                retainedEquipmentInfo.setStoreNum(totalStoreNum);
                retainedEquipmentInfo.setUsNum(totalUsNum);
                retainedEquipmentInfo.setDsNum(totalDsNum);
                retainedEquipmentInfo.setRepairNum(totalRepairNum);
                retainedEquipmentInfo.setRepairAuditNum(totalRepairAuditNum);
                retainedEquipmentInfo.setInputNum(totalInputNum);
                retainedEquipmentInfo.setRepairInputNum(totalRepairInputNum);
                retainedEquipmentInfo.setPendingScrapNum(totalPendingScrapNum);
                retainedEquipmentInfo.setScrapNum(totalScrapNum);
                retainedEquipmentInfo.setAllNum(totalAllNum);
                retainedEquipmentInfo.setTotalPrice(totalPrice);
                /*retainedEquipmentInfo.setFiveReplacementRate(fiveReplacementRate);
                retainedEquipmentInfo.setTenReplacementRate(tenReplacementRate);
                retainedEquipmentInfo.setTenPlusReplacementRate(tenPlusReplacementRate);*/
                retainedEquipmentInfo.setUnit("合计");
                recordList.add(0, retainedEquipmentInfo);
            }
        }
        return recordList;
    }

    /**
     * 查询机具编码
     *
     * @param bean
     * @return
     */
    @Override
    public List<StorageInfo> getMaCodeList(StorageInfo bean) {
        List<StorageInfo> recordList = complexQueryMapper.getMaCodeList(bean);
        List<StorageInfo> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(recordList)) {
            for (StorageInfo storageInfo : recordList) {
                if (StringUtils.isNotBlank(storageInfo.getMaCode())) {
                    String[] split = storageInfo.getMaCode().split(",");
                    if (split.length > 1) {
                        for (String code : split) {
                            StorageInfo newRecord = new StorageInfo();
                            BeanUtils.copyProperties(storageInfo, newRecord);
                            newRecord.setMaCode(code);
                            newRecord.setStoreNum(BigDecimal.ONE);
                            list.add(newRecord);
                        }
                    } else {
                        list.add(storageInfo);
                    }
                } else {
                    list.add(storageInfo);
                }
            }
        }
        extracted(list);
        // 查询在库具体编码code
        List<StorageInfo> codeList = complexQueryMapper.selectMaCodeByTypeId(bean);
        // 1. 创建一个 Set 存储 codeList 中的 typeId 和 maCode 的组合键
        Set<String> validCodes = codeList.stream()
                .filter(code -> code.getTypeId() != null && code.getMaCode() != null)
                .map(code -> code.getTypeId() + "-" + code.getMaCode())
                .collect(Collectors.toSet());

        if (CollectionUtil.isNotEmpty(codeList) && CollectionUtil.isNotEmpty(list)) {
            list = list.stream()
                    .filter(item -> validCodes.contains(item.getTypeId() + "-" + item.getMaCode()))
                    .collect(Collectors.toList());
        }
        if (StringUtils.isNotBlank(bean.getKeyWord())) {
            String keyword = bean.getKeyWord();
            return list.stream().filter(item -> {
                return (StringUtils.isNotBlank(item.getMaCode()) && item.getMaCode().contains(keyword)) ||
                        (StringUtils.isNotBlank(item.getTypeName()) && item.getTypeName().contains(keyword)) ||
                        (StringUtils.isNotBlank(item.getTypeModelName()) && item.getTypeModelName().contains(keyword)) ||
                        (StringUtils.isNotBlank(item.getInputUser()) && item.getInputUser().contains(keyword)) ||
                        (StringUtils.isNotBlank(item.getMaKeeper()) && item.getMaKeeper().contains(keyword)) ||
                        (StringUtils.isNotBlank(item.getInputType()) && item.getInputType().contains(keyword));
            }).collect(Collectors.toList());
        }
        return list;
    }

    /**
     * 去重maCode，保留最新的一个
     *
     * @param list
     */
    private void extracted(List<StorageInfo> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            Map<String, StorageInfo> map = new HashMap<>();
            for (StorageInfo storageInfo : list) {
                String maCode = storageInfo.getMaCode();
                // 如果map中没有这个maCode，直接添加
                if (!map.containsKey(maCode)) {
                    map.put(maCode, storageInfo);
                } else {
                    // 如果map中已经有这个maCode，比较inputTime
                    StorageInfo existing = map.get(maCode);

                    // 如果当前的storageInfo的inputTime更晚，更新map中的值
                    if (storageInfo.getInputTime().after(existing.getInputTime())) {
                        map.put(maCode, storageInfo);
                    }
                }
            }
            // 最后将map中的所有最新的StorageInfo对象放入list
            list.clear();
            list.addAll(map.values());
        }
    }

    /**
     * 查询在用设备详情
     *
     * @param bean
     * @return
     */
    @Override
    public List<UseStorageInfo> getUserRecords(UseStorageInfo bean) {
        try {
            List<UseStorageInfo> list = complexQueryMapper.getUserRecords(bean);
            if (CollectionUtils.isNotEmpty(list)) {
                // 提取所有非空的leaseId，批量查询出库信息
                Set<Long> leaseIds = list.stream()
                        .map(UseStorageInfo::getLeaseId)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toSet());

                // 批量查询并缓存结果，减少数据库交互
                Map<Long, UseStorageInfo> leaseInfoMap = Collections.emptyMap();
                if (!leaseIds.isEmpty()) {
                    List<UseStorageInfo> queryResults = complexQueryMapper.batchSelectInfo(leaseIds);
                    leaseInfoMap = queryResults.stream()
                            // 先过滤掉null元素，避免后续调用方法时空指针
                            .filter(Objects::nonNull)
                            // 再过滤LeaseId为null的元素
                            .filter(info -> info.getLeaseId() != null)
                            .collect(Collectors.toMap(
                                    UseStorageInfo::getLeaseId,
                                    info -> info,
                                    (existing, replacement) -> existing  // 遇到重复key时保留第一个值
                            ));
                }
                // 批量设置出库信息
                Map<Long, UseStorageInfo> finalLeaseInfoMap = leaseInfoMap;
                list.forEach(useStorageInfo -> {
                    Object leaseId = useStorageInfo.getLeaseId();
                    if (leaseId != null) {
                        UseStorageInfo dto = finalLeaseInfoMap.get(leaseId);
                        if (dto != null) {
                            useStorageInfo.setCreator(dto.getCreator());
                            useStorageInfo.setOutTime(dto.getOutTime());
                        }
                    }
                });
                String keyWord = bean.getKeyWord();
                // 如果关键字不为空，进行过滤
                if (!com.bonus.common.core.utils.StringUtils.isBlank(keyWord)) {
                    list = list.stream()
                            .filter(item -> containsKeyword(item, keyWord))
                            .collect(Collectors.toList());
                }
            }
            return list;
        } catch (Exception e) {
            log.error("查询在用设备详情失败", e);
            throw new RuntimeException("查询在用设备详情失败");
        }
    }

    /**
     * 判断item是否包含关键字
     *
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsKeyword(UseStorageInfo item, String keyWord) {
        return (item.getTypeName() != null && item.getTypeName().contains(keyWord)) ||
                (item.getTypeModelName() != null && item.getTypeModelName().contains(keyWord)) ||
                (item.getCreator() != null && item.getCreator().equals(keyWord)) ||
                (item.getMaCode() != null && item.getMaCode().contains(keyWord)) ||
                (item.getProjectName() != null && item.getProjectName().contains(keyWord)) ||
                (item.getCode() != null && item.getCode().contains(keyWord));
    }

    /**
     * 查询在修设备详情
     *
     * @param bean
     * @return
     */
    @Override
    public List<RepairStorageInfo> getRepairRecordList(RepairStorageInfo bean) {
        List<RepairStorageInfo> list = new ArrayList<>();
        if (bean.getType() != null && (bean.getType() == 1 || bean.getType() == 2)) {
            list = complexQueryMapper.getRepairRecordList(bean);
        }
        if (bean.getType() != null && bean.getType() == 3) {
            list = complexQueryMapper.getRepairAuditList(bean);
        }
        return list;
    }

    /**
     * 查询新购待入库设备详情
     *
     * @param bean
     * @return
     */
    @Override
    public List<PurchaseInputInfo> getPurchaseRecordList(PurchaseInputInfo bean) {
        List<PurchaseInputInfo> recordList = complexQueryMapper.getPurchaseRecordList(bean);
        List<PurchaseInputInfo> tempList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(recordList)) {
            if (MaTypeManageTypeEnum.NUMBER_DEVICE.getTypeId().toString().equals(recordList.get(0).getManageType())) {
                if (StringUtils.isNotBlank(bean.getKeyWord())) {
                    String keyword = bean.getKeyWord();
                    return recordList.stream().filter(item -> {
                        return (StringUtils.isNotBlank(item.getCode()) && item.getCode().contains(keyword)) ||
                                (StringUtils.isNotBlank(item.getTypeName()) && item.getTypeName().contains(keyword)) ||
                                (StringUtils.isNotBlank(item.getTypeModelName()) && item.getTypeModelName().contains(keyword)) ||
                                (StringUtils.isNotBlank(item.getMaKeeper()) && item.getMaKeeper().contains(keyword));
                    }).collect(Collectors.toList());
                }
                return recordList;
            } else {
                Iterator<PurchaseInputInfo> iterator = recordList.iterator();
                while (iterator.hasNext()) {
                    PurchaseInputInfo purchaseInputInfo = iterator.next();
                    // 根据任务id和类型id查询未入库编码信息
                    List<PurchaseInputInfo> maCodeList = complexQueryMapper.selectMaCodeByTaskIdAndTypeId(purchaseInputInfo.getTaskId(), bean.getTypeId());
                    if (CollectionUtils.isNotEmpty(maCodeList)) {
                        boolean addedPurchaseInputInfo = false;
                        for (PurchaseInputInfo info : maCodeList) {
                            if (purchaseInputInfo.getInputNum().compareTo(BigDecimal.valueOf(maCodeList.size())) > 0) {
                                purchaseInputInfo.setInputNum(purchaseInputInfo.getInputNum().subtract(BigDecimal.valueOf(maCodeList.size())));
                                String maCode = info.getMaCode();
                                BeanUtils.copyProperties(purchaseInputInfo, info);
                                info.setMaCode(maCode);
                                info.setInputNum(BigDecimal.ONE);
                                tempList.add(info);
                                if (!addedPurchaseInputInfo) {
                                    tempList.add(purchaseInputInfo);
                                    addedPurchaseInputInfo = true;
                                }
                            } else if (purchaseInputInfo.getInputNum().compareTo(BigDecimal.valueOf(maCodeList.size())) == 0) {
                                String maCode = info.getMaCode();
                                BeanUtils.copyProperties(purchaseInputInfo, info);
                                info.setMaCode(maCode);
                                info.setInputNum(BigDecimal.ONE);
                                tempList.add(info);
                            }
                        }
                    }
                }
            }
        }
        if (StringUtils.isNotBlank(bean.getKeyWord())) {
            String keyword = bean.getKeyWord();
            return tempList.stream().filter(item -> {
                return (StringUtils.isNotBlank(item.getMaCode()) && item.getMaCode().contains(keyword)) ||
                        (StringUtils.isNotBlank(item.getTypeName()) && item.getTypeName().contains(keyword)) ||
                        (StringUtils.isNotBlank(item.getTypeModelName()) && item.getTypeModelName().contains(keyword)) ||
                        (StringUtils.isNotBlank(item.getCode()) && item.getCode().contains(keyword)) ||
                        (StringUtils.isNotBlank(item.getMaKeeper()) && item.getMaKeeper().contains(keyword));
            }).collect(Collectors.toList());
        }
        return tempList;
    }

    /**
     * 查询修饰待入库设备详情
     *
     * @param bean
     * @return
     */
    @Override
    public List<RepairInputRecord> getRepairInputList(RepairInputRecord bean) {
        return complexQueryMapper.getRepairInputList(bean);
    }

    /**
     * 查询待报废设备详情
     *
     * @param bean
     * @return
     */
    @Override
    public List<ScrapRecordInfo> getScrapList(ScrapRecordInfo bean) {
        return complexQueryMapper.getScrapList(bean);
    }

    /**
     * 查询已审核报废设备详情
     *
     * @param bean
     * @return
     */
    @Override
    public List<ScrapAuditInfo> getScrapAuditList(ScrapAuditInfo bean) {
        return complexQueryMapper.getScrapAuditList(bean);
    }

    /**
     * 修试查询--一机一档案查询
     *
     * @param bean
     * @return
     */
    @Override
    public List<MaTypeSelectInfo> getMaTypeSelectList(MaTypeSelectInfo bean) {
        List<MaTypeSelectInfo> recordList = complexQueryMapper.getMaTypeSelectList(bean);
        List<MaTypeSelectInfo> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(recordList)) {
            for (MaTypeSelectInfo dto : recordList) {
                if (StringUtils.isNotBlank(dto.getMaCode())) {
                    String[] split = dto.getMaCode().split(",");
                    if (split.length > 1) {
                        for (String code : split) {
                            MaTypeSelectInfo newRecord = new MaTypeSelectInfo();
                            BeanUtils.copyProperties(dto, newRecord);
                            newRecord.setMaCode(code);
                            list.add(newRecord);
                        }
                    } else {
                        list.add(dto);
                    }
                } else {
                    list.add(dto);
                }
                // 领用申请
                if (dto.getTaskType() == 19) {
                    // 根据id查询单位、工程及协议信息
                    MaTypeSelectInfo vo = complexQueryMapper.selectUnitAndProAndAgreementInfo(dto);
                    if (vo != null) {
                        dto.setAgreementCode(StringUtils.isNotBlank(vo.getAgreementCode()) ? vo.getAgreementCode() : "");
                        dto.setBmUnitName(StringUtils.isNotBlank(vo.getBmUnitName()) ? vo.getBmUnitName() : "");
                        dto.setBmProName(StringUtils.isNotBlank(vo.getBmProName()) ? vo.getBmProName() : "");
                    }
                }
                // 查询收费配件信息
                if (dto.getTaskType() == 4) {
                    String result = complexQueryMapper.getPartInfoList(dto);
                    if (StringUtils.isNotBlank(result)) {
                        dto.setOperationInfo(result);
                    }
                }
            }
        }
        // 根据关键字搜索查询
        if (CollectionUtils.isNotEmpty(list)) {
            if (StringUtils.isNotBlank(bean.getKeyWord())) {
                String keyWord = bean.getKeyWord();
                return list.stream().filter(item -> {
                    return (StringUtils.isNotBlank(item.getMaCode()) && item.getMaCode().contains(keyWord)) ||
                            (StringUtils.isNotBlank(item.getTypeName()) && item.getTypeName().contains(keyWord)) ||
                            (StringUtils.isNotBlank(item.getTypeModelName()) && item.getTypeModelName().contains(keyWord)) ||
                            (StringUtils.isNotBlank(item.getAgreementCode()) && item.getAgreementCode().contains(keyWord)) ||
                            (StringUtils.isNotBlank(item.getBmUnitName()) && item.getBmUnitName().contains(keyWord)) ||
                            (StringUtils.isNotBlank(item.getBmProName()) && item.getBmProName().contains(keyWord)) ||
                            (StringUtils.isNotBlank(item.getCode()) && item.getCode().contains(keyWord)) ||
                            (StringUtils.isNotBlank(item.getCreateBy()) && item.getCreateBy().contains(keyWord)) ||
                            (StringUtils.isNotBlank(item.getOperationInfo()) && item.getOperationInfo().contains(keyWord)) ||
                            (StringUtils.isNotBlank(item.getOperationType()) && item.getOperationType().contains(keyWord));
                }).collect(Collectors.toList());
            }
        }
        return list;
    }

    /**
     * 机具库存个人查询
     * @param bean
     * @return
     */
    @Override
    public List<RetainedEquipmentInfo> getPersonNum(RetainedEquipmentInfo bean) {
        Long userId = SecurityUtils.getLoginUser().getUserid();
        bean.setUserId(userId);
        return complexQueryMapper.getPersonNum(bean);
    }

    @Override
    public List<ProjUsingRecord> getStatisticsList(ProjUsingRecord bean) {
        try {
            // 1、查询工程对应的物资名称、型号、需求数量、已供数量
            List<ProjUsingRecord> list = complexQueryMapper.getStatisticsList(bean);

            // 创建缓存Map，key为typeId，value为对应的库存信息
            Map<Long, RetainedEquipmentInfo> inventoryCache = new HashMap<>();

            for (ProjUsingRecord item : list) {
                // 2、计算需求数量，已供数量的差值
                BigDecimal needNum = new BigDecimal(item.getNeedNum());
                BigDecimal supplyNum = new BigDecimal(item.getSupplyNum());
                BigDecimal diffNum = needNum.subtract(supplyNum);
                item.setDiffNum(diffNum.toString());

                // 3、查询该工程设备的在用数量
                ProjUsingRecord projUsingRecord3 = complexQueryMapper.getUsNum(item);
                if (projUsingRecord3 != null && projUsingRecord3.getUsNum() != null) {
                    item.setUsNum(projUsingRecord3.getUsNum());
                } else {
                    item.setUsNum(BigDecimal.ZERO);
                }

                // 4、根据typeId查询库存信息（使用缓存优化）
                Long typeId = Long.valueOf(item.getTypeId());

                RetainedEquipmentInfo bean1 = inventoryCache.get(typeId);
                if (bean1 == null) {
                    // 如果缓存中没有，则查询数据库并放入缓存
                    bean1 = complexQueryMapper.selectInventory(item);
                    inventoryCache.put(typeId, bean1);
                }

                // 设置库存相关信息
                item.setStoreNum(bean1.getStoreNum());
                item.setRepairNum(bean1.getRepairNum());
                item.setAllUsNum(bean1.getUsNum());

                // 使用三元运算符处理null值
                BigDecimal inputNum = bean1.getInputNum() != null ? bean1.getInputNum() : BigDecimal.ZERO;
                BigDecimal repairInputNum = bean1.getRepairInputNum() != null ? bean1.getRepairInputNum() : BigDecimal.ZERO;
                item.setInputNum(inputNum.add(repairInputNum));
                item.setAllNum(bean1.getAllNum());
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public List<ProjUsingRecord> getAllUsDetails(ProjUsingRecord bean) {
        try {
            return complexQueryMapper.getAllUsDetails(bean);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    /**
     * 配件库存个人查询
     * @param bean
     * @return
     */
    @Override
    public List<RetainedEquipmentInfo> getPartPersonNum(RetainedEquipmentInfo bean) {
        Long userId = SecurityUtils.getLoginUser().getUserid();
        bean.setUserId(userId);
        return complexQueryMapper.getPartPersonNum(bean);
    }

    @Override
    public List<Type> getStorageNumLogList(Type bean) {
        try {
            List<Type> list = complexQueryMapper.getStorageNumLogList(bean);
            for (Type item : list){
                /* 根据开始、结束时间，查询昨日库存、当日库存
                 * 昨日库存是开始时间之前的库存，当前库存是结束时间的库存
                 * 昨日库存逻辑梳理：
                 *      1、正常情况：查询开始日期之前日志表最后的库存
                 *      2、如果开始日期之前表里没数据，查询开始日期之后该类型的第一条数据的开始库存
                 *      3、如果开始之前和结束日期之后都没有此类型，则使用当前库存
                 * 当前库存逻辑梳理：
                 *      1、正常情况：查询结束日期的库存
                 *      2、如果结束日期没有数据，查询结束日期后，该类型的第一条数据的开始库存
                 *      3、如果开始日期和结束日期都没有此类型，则使用当前库存
                 */
                item.setStartTime(bean.getStartTime());
                item.setEndTime(bean.getEndTime());
                if (bean.getStartTime() != null && bean.getEndTime() != null){
                    //昨日库存
                    Type yesterdayStorageNum = complexQueryMapper.getYesterdayStorageNum(item);
                    if (yesterdayStorageNum != null){
                        if (yesterdayStorageNum.getAfterStoreNum()!=null){
                            item.setPreStoreNum(yesterdayStorageNum.getAfterStoreNum());
                        } else {
                            item.setPreStoreNum(yesterdayStorageNum.getPreStoreNum());
                        }
                    } else {
                        item.setPreStoreNum(item.getStorageNum());
                    }
                    //当前库存
                    Type storageNum = complexQueryMapper.getNewStorageNum(item);
                    if (storageNum != null){
                        if (storageNum.getAfterStoreNum()!=null){
                            item.setAfterStoreNum(storageNum.getAfterStoreNum());
                        } else {
                            item.setAfterStoreNum(storageNum.getPreStoreNum());
                        }
                    } else {
                        item.setAfterStoreNum(item.getStorageNum());
                    }
                } else {
                    //没有时间，查总的。昨日库存为第一条数据的改前库存，当前库存为最后一条数据的改后库存
                    Type totalStorageNum = complexQueryMapper.getTotalStorageNumLog(item);
                    if (totalStorageNum != null){
                        item.setPreStoreNum(totalStorageNum.getPreStoreNum());
                        item.setAfterStoreNum(totalStorageNum.getAfterStoreNum());
                    } else {
                        //为空的，则使用当前库存
                        item.setPreStoreNum(item.getStorageNum());
                        item.setAfterStoreNum(item.getStorageNum());
                    }
                }
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public List<Type> getStorageNumLogDetails(Type bean) {
        try {
            return complexQueryMapper.getStorageNumLogDetails(bean);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
}
