package com.zksy.base.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.base.domain.*;
import com.zksy.base.mapper.*;
import com.zksy.base.alarm.domain.WarningThreshold;
import com.zksy.base.alarm.mapper.WarningThresholdMapper;
import com.zksy.base.domain.EquipmentBase;
import com.zksy.base.domain.EquipmentMaintain;
import com.zksy.base.domain.EquipmentStatus;
import com.zksy.base.domain.EquipmentType;
import com.zksy.base.manhole.domain.ManholeData;
import com.zksy.base.manhole.mapper.ManholeDataMapper;
import com.zksy.base.mapper.EquipmentBaseMapper;
import com.zksy.base.mapper.EquipmentMaintainMapper;
import com.zksy.base.mapper.EquipmentStatusMapper;
import com.zksy.base.mapper.EquipmentTypeMapper;
import com.zksy.base.service.EquipmentBaseService;
import com.zksy.common.exception.ServiceException;
import com.zksy.manhole.dto.in.ManholeDeviceListInDTO;
import com.zksy.manhole.dto.in.ManholeDevicePageInDTO;
import com.zksy.manhole.dto.out.EquipmentBaseOutDTO;
import com.zksy.manhole.dto.out.EquipmentStatusOutDTO;
import com.zksy.manhole.dto.out.ManholeDataOutDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class EquipmentBaseServiceImpl extends ServiceImpl<EquipmentBaseMapper, EquipmentBase>
        implements EquipmentBaseService {

    @Autowired
    private EquipmentTypeMapper equipmentTypeMapper;

    @Autowired
    private EquipmentMaintainMapper equipmentMaintainMapper;

    @Autowired
    private EquipmentStatusMapper equipmentStatusMapper;

    @Autowired
    private EquipmentPointRelMapper equipmentPointRelMapper;

    @Autowired
    private EquipmentTestMapper equipmentTestMapper;

    @Autowired
    private WarningThresholdMapper warningThresholdMapper;

    @Autowired
    private ManholeDataMapper manholeDataMapper;

    @Override
    public Page<EquipmentBase> findByPage(long pageNum, long pageSize,
                                          String equipmentCode, String equipmentName,
                                          String equipmentModel, String manufacturer) {
        Page<EquipmentBase> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<EquipmentBase> queryWrapper = new LambdaQueryWrapper<>();
        if (equipmentCode != null && !equipmentCode.isEmpty()) {
            queryWrapper.like(EquipmentBase::getEquipmentCode, equipmentCode);
        }
        if (equipmentName != null && !equipmentName.isEmpty()) {
            queryWrapper.like(EquipmentBase::getEquipmentName, equipmentName);
        }
        if (equipmentModel != null && !equipmentModel.isEmpty()) {
            queryWrapper.like(EquipmentBase::getEquipmentModel, equipmentModel);
        }
        if (manufacturer != null && !manufacturer.isEmpty()) {
            queryWrapper.like(EquipmentBase::getManufacturer, manufacturer);
        }
        queryWrapper.orderByDesc(EquipmentBase::getCreateTime);
        return this.page(page, queryWrapper);
    }

    @Override
    public boolean saveWithCheck(EquipmentBase entity) {
        String equipmentTypeId = entity.getEquipmentTypeId();
        EquipmentType equipmentType = equipmentTypeMapper.selectById(equipmentTypeId);
        if (equipmentType == null) {
            throw new ServiceException("设备类型不存在，请检查equipment_type_id：");
        }
        LambdaQueryWrapper<EquipmentBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EquipmentBase::getEquipmentCode, entity.getEquipmentCode());
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new ServiceException("设备编码已存在，请更换：" + entity.getEquipmentCode());
        }
        return this.save(entity);
    }

    @Override
    public boolean saveBatchWithCheck(List<EquipmentBase> entityList) {
        Set<String> codeSet = new HashSet<>();
        for (EquipmentBase entity : entityList) {
            String code = entity.getEquipmentCode();
            if (codeSet.contains(code)) {
                throw new ServiceException("列表中存在重复编码：" + code);
            }
            codeSet.add(code);
        }

        for (EquipmentBase entity : entityList) {
            if (equipmentTypeMapper.selectById(entity.getEquipmentTypeId()) == null) {
                throw new ServiceException("设备类型不存在：" + entity.getEquipmentTypeId());
            }
            LambdaQueryWrapper<EquipmentBase> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(EquipmentBase::getEquipmentCode, entity.getEquipmentCode());
            if (this.count(wrapper) > 0) {
                throw new ServiceException("设备编码已存在：" + entity.getEquipmentCode());
            }
        }
        return this.saveBatch(entityList);
    }

    @Override
    @Transactional
    public boolean updateWithCheck(EquipmentBase entity) {
        String equipmentId = entity.getEquipmentId();
        if (this.getById(equipmentId) == null) {
            throw new ServiceException("设备不存在，无法修改：" + equipmentId);
        }

        String newTypeId = entity.getEquipmentTypeId();
        if (newTypeId != null && equipmentTypeMapper.selectById(newTypeId) == null) {
            throw new ServiceException("设备类型不存在：" + newTypeId);
        }

        String newCode = entity.getEquipmentCode();
        if (newCode != null) {
            LambdaQueryWrapper<EquipmentBase> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(EquipmentBase::getEquipmentCode, newCode)
                    .ne(EquipmentBase::getEquipmentId, equipmentId);
            if (this.count(wrapper) > 0) {
                throw new ServiceException("设备编码已被使用：" + newCode);
            }
        }
        return this.updateById(entity);
    }

    @Override
    @Transactional
    public boolean removeWithCheck(String equipmentId) {
        EquipmentBase equipment = this.getById(equipmentId);
        if (equipment == null) {
            throw new ServiceException("设备不存在：" + equipmentId);
        }

        LambdaQueryWrapper<EquipmentMaintain> maintainWrapper = new LambdaQueryWrapper<>();
        maintainWrapper.eq(EquipmentMaintain::getEquipmentId, equipmentId);
        equipmentMaintainMapper.delete(maintainWrapper);
        log.info("已删除设备[{}]的维护记录", equipmentId);

        LambdaQueryWrapper<EquipmentStatus> statusWrapper = new LambdaQueryWrapper<>();
        statusWrapper.eq(EquipmentStatus::getEquipmentId, equipmentId);
        equipmentStatusMapper.delete(statusWrapper);
        log.info("已删除设备[{}]的状态记录", equipmentId);

        LambdaQueryWrapper<EquipmentPointRel> relWrapper = new LambdaQueryWrapper<>();
        relWrapper.eq(EquipmentPointRel::getEquipmentId, equipmentId);
        equipmentPointRelMapper.delete(relWrapper);
        log.info("已删除设备[{}]的监测点关联", equipmentId);

        // 现在 WarningThreshold 有了 equipmentId 字段，直接匹配
        LambdaQueryWrapper<WarningThreshold> thresholdWrapper = new LambdaQueryWrapper<>();
        thresholdWrapper.eq(WarningThreshold::getEquipmentId, equipmentId);
        warningThresholdMapper.delete(thresholdWrapper);
        log.info("已删除设备[{}]的预警阈值配置", equipmentId);

        LambdaQueryWrapper<EquipmentTest> testWrapper = new LambdaQueryWrapper<>();
        testWrapper.eq(EquipmentTest::getEquipmentId, equipmentId);
        equipmentTestMapper.delete(testWrapper);
        log.info("已删除设备[{}]的测试记录", equipmentId);

        return this.baseMapper.deleteById(equipmentId) > 0;
    }

    @Override
    @Transactional
    public boolean removeBatchWithCheck(List<String> equipmentIds) {
        if (CollectionUtils.isEmpty(equipmentIds)) {
            throw new ServiceException("批量删除失败：设备ID列表不能为空");
        }

        List<EquipmentBase> existEquipments = this.listByIds(equipmentIds);
        if (existEquipments.isEmpty()) {
            throw new ServiceException("批量删除失败：所有设备ID均不存在");
        }
        List<String> existIds = existEquipments.stream()
                .map(EquipmentBase::getEquipmentId)
                .collect(Collectors.toList());

        List<String> invalidIds = equipmentIds.stream()
                .filter(id -> !existIds.contains(id))
                .collect(Collectors.toList());
        if (!invalidIds.isEmpty()) {
            log.warn("批量删除中存在无效设备ID：{}", invalidIds);
        }

        LambdaQueryWrapper<EquipmentMaintain> maintainWrapper = new LambdaQueryWrapper<>();
        maintainWrapper.in(EquipmentMaintain::getEquipmentId, existIds);
        equipmentMaintainMapper.delete(maintainWrapper);
        log.info("已批量删除{}条设备的维护记录", existIds.size());

        LambdaQueryWrapper<EquipmentStatus> statusWrapper = new LambdaQueryWrapper<>();
        statusWrapper.in(EquipmentStatus::getEquipmentId, existIds);
        equipmentStatusMapper.delete(statusWrapper);
        log.info("已批量删除{}条设备的状态记录", existIds.size());

        LambdaQueryWrapper<EquipmentPointRel> relWrapper = new LambdaQueryWrapper<>();
        relWrapper.in(EquipmentPointRel::getEquipmentId, existIds);
        equipmentPointRelMapper.delete(relWrapper);
        log.info("已批量删除{}条设备的监测点关联", existIds.size());

        // 现在 WarningThreshold 有了 equipmentId 字段，直接匹配
        LambdaQueryWrapper<WarningThreshold> thresholdWrapper = new LambdaQueryWrapper<>();
        thresholdWrapper.in(WarningThreshold::getEquipmentId, existIds);
        warningThresholdMapper.delete(thresholdWrapper);
        log.info("已批量删除{}条设备的预警阈值配置", existIds.size());

        LambdaQueryWrapper<EquipmentTest> testWrapper = new LambdaQueryWrapper<>();
        testWrapper.in(EquipmentTest::getEquipmentId, existIds);
        equipmentTestMapper.delete(testWrapper);
        log.info("已批量删除{}条设备的测试记录", existIds.size());

        return this.removeByIds(existIds);
    }

    /**
     * 分页查询监测设备台账列表
     * @param pageInDTO
     * @return
     */
    @Override
    public Page<EquipmentBaseOutDTO> findManholeDeviceByPage(ManholeDevicePageInDTO pageInDTO) {
        log.info("分页查询监测设备台账列表-入参:{}", pageInDTO);
        List<String> equipmentIds = null;
        if(pageInDTO.getCurrentStatus() != null){
            List<EquipmentStatus> equipmentStatusList = equipmentStatusMapper.selectList(new LambdaQueryWrapper<EquipmentStatus>()
                    .eq(EquipmentStatus::getCurrentStatus, pageInDTO.getCurrentStatus()));
            if(CollUtil.isEmpty(equipmentStatusList)){
                return new Page<>(pageInDTO.getPageNum(), pageInDTO.getPageSize(), 0);
            }
            equipmentIds = equipmentStatusList.stream().map(EquipmentStatus::getEquipmentId).distinct().collect(Collectors.toList());
        }
        Page<EquipmentBase> page = new Page<>(pageInDTO.getPageNum(), pageInDTO.getPageSize());
        LambdaQueryWrapper<EquipmentBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(pageInDTO.getDeviceCode()), EquipmentBase::getEquipmentCode, pageInDTO.getDeviceCode())
                .eq(StringUtils.isNotEmpty(pageInDTO.getEquipmentTypeId()), EquipmentBase::getEquipmentTypeId, pageInDTO.getEquipmentTypeId())
                .in(CollUtil.isNotEmpty(equipmentIds), EquipmentBase::getEquipmentId, equipmentIds)
                .like(StringUtils.isNotEmpty(pageInDTO.getDeviceName()), EquipmentBase::getEquipmentName, pageInDTO.getDeviceName())
                .like(StringUtils.isNotEmpty(pageInDTO.getEquipmentLocation()), EquipmentBase::getEquipmentLocation, pageInDTO.getEquipmentLocation())
                .orderByDesc(EquipmentBase::getUpdateTime);
        Page<EquipmentBase> rs = this.page(page, queryWrapper);
        List<EquipmentBaseOutDTO> outDTOList = BeanUtil.copyToList(rs.getRecords(), EquipmentBaseOutDTO.class);
        if (CollUtil.isNotEmpty(outDTOList)) {
            //查询设备类型
            List<String> equipmentTypeIdList = outDTOList.stream().map(EquipmentBaseOutDTO::getEquipmentTypeId).distinct().collect(Collectors.toList());
            List<EquipmentType> equipmentTypeList = equipmentTypeMapper.selectBatchIds(equipmentTypeIdList);
            Map<String, EquipmentType> equipmentTypeMap = new HashMap<>();
            if(CollUtil.isNotEmpty(equipmentTypeList)){
                equipmentTypeMap.putAll(equipmentTypeList.stream().collect(Collectors.toMap(EquipmentType::getTypeId, Function.identity(), (key1, key2) -> key2)));
            }
            //查询设备状态
            List<String> equipmentIdList = outDTOList.stream().map(EquipmentBaseOutDTO::getEquipmentId).distinct().collect(Collectors.toList());
            List<EquipmentStatus> equipmentStatusList = equipmentStatusMapper.selectList(new LambdaQueryWrapper<EquipmentStatus>()
                    .in(EquipmentStatus::getEquipmentId, equipmentIdList));
            Map<String, EquipmentStatus> EquipmentStatusMap = new HashMap<>();
            if(CollUtil.isNotEmpty(equipmentStatusList)){
                EquipmentStatusMap.putAll(equipmentStatusList.stream().collect(Collectors.toMap(EquipmentStatus::getEquipmentId, Function.identity(), (key1, key2) -> key2)));
            }
            //查询设备监测状态
            Map<String, List<ManholeData>> imeiCardNumberMapList = new HashMap<>();
            if(pageInDTO.getIsQueryManholeData()){
                List<String> equipmentCodeList = outDTOList.stream().map(EquipmentBaseOutDTO::getEquipmentCode).distinct().collect(Collectors.toList());
                List<ManholeData> manholeDataList = manholeDataMapper.selectList(new LambdaQueryWrapper<ManholeData>()
                        .in(ManholeData::getImeiCardNumber, equipmentCodeList)
                        .orderByDesc(ManholeData::getCreateTime));
                imeiCardNumberMapList.putAll(manholeDataList.stream().collect(Collectors.groupingBy(ManholeData::getImeiCardNumber)));
            }
            List<ManholeData> manholeDataList = null;
            for(EquipmentBaseOutDTO outDTO : outDTOList) {
                EquipmentType equipmentType = equipmentTypeMap.get(outDTO.getEquipmentTypeId());
                if(equipmentType != null){
                    outDTO.setEquipmentTypeName(equipmentType.getTypeName());
                }
                EquipmentStatus equipmentStatus = EquipmentStatusMap.get(outDTO.getEquipmentId());
                if(equipmentStatus != null){
                    EquipmentStatusOutDTO equipmentStatusOutDTO = BeanUtil.copyProperties(equipmentStatus, EquipmentStatusOutDTO.class);
                    outDTO.setEquipmentStatus(equipmentStatusOutDTO);
                }
                if(pageInDTO.getIsQueryManholeData()){
                    manholeDataList = imeiCardNumberMapList.get(outDTO.getEquipmentCode());
                    if(CollUtil.isNotEmpty(manholeDataList)){
                        ManholeData manholeData = manholeDataList.get(0);
                        ManholeDataOutDTO manholeDataOutDTO = BeanUtil.copyProperties(manholeData, ManholeDataOutDTO.class);
                        outDTO.setManholeData(manholeDataOutDTO);
                    }
                }
            }
        }
        Page<EquipmentBaseOutDTO> outPage = new Page<>(pageInDTO.getPageNum(), pageInDTO.getPageSize(), rs.getTotal());
        outPage.setRecords(outDTOList);
        return outPage;
    }

    /**
     * 查询井盖监测设备列表
     * @param listInDTO
     * @return
     */
    @Override
    public List<EquipmentBaseOutDTO> getManholeDataList(ManholeDeviceListInDTO listInDTO) {
        log.info("查询井盖监测设备列表-入参:{}", listInDTO);
        List<String> equipmentIds = null;
        if(listInDTO.getCurrentStatus() != null || listInDTO.getAlarmStatus() != null || listInDTO.getOnlineStatus() != null){
            List<EquipmentStatus> equipmentStatusList = equipmentStatusMapper.selectList(new LambdaQueryWrapper<EquipmentStatus>()
                    .eq(listInDTO.getCurrentStatus() != null, EquipmentStatus::getCurrentStatus, listInDTO.getCurrentStatus())
                    .eq(listInDTO.getAlarmStatus() != null, EquipmentStatus::getAlarmStatus, listInDTO.getAlarmStatus())
                    .eq(listInDTO.getOnlineStatus() != null, EquipmentStatus::getOnlineStatus, listInDTO.getOnlineStatus()));
            if(CollUtil.isEmpty(equipmentStatusList)){
                return new ArrayList<>();
            }
            equipmentIds = equipmentStatusList.stream().map(EquipmentStatus::getEquipmentId).distinct().collect(Collectors.toList());
        }
        LambdaQueryWrapper<EquipmentBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(CollUtil.isNotEmpty(equipmentIds), EquipmentBase::getEquipmentId, equipmentIds)
                .orderByDesc(EquipmentBase::getUpdateTime);
        List<EquipmentBase> equipmentBaseList = this.list(queryWrapper);
        if (CollUtil.isEmpty(equipmentBaseList)) {
            return new ArrayList<>();
        }
        List<EquipmentBaseOutDTO> outDTOList = BeanUtil.copyToList(equipmentBaseList, EquipmentBaseOutDTO.class);
        //查询设备类型
        List<String> equipmentTypeIdList = outDTOList.stream().map(EquipmentBaseOutDTO::getEquipmentTypeId).distinct().collect(Collectors.toList());
        List<EquipmentType> equipmentTypeList = equipmentTypeMapper.selectBatchIds(equipmentTypeIdList);
        Map<String, EquipmentType> equipmentTypeMap = new HashMap<>();
        if(CollUtil.isNotEmpty(equipmentTypeList)){
            equipmentTypeMap.putAll(equipmentTypeList.stream().collect(Collectors.toMap(EquipmentType::getTypeId, Function.identity(), (key1, key2) -> key2)));
        }
        //查询设备状态
        List<String> equipmentIdList = outDTOList.stream().map(EquipmentBaseOutDTO::getEquipmentId).distinct().collect(Collectors.toList());
        List<EquipmentStatus> equipmentStatusList = equipmentStatusMapper.selectList(new LambdaQueryWrapper<EquipmentStatus>()
                .in(EquipmentStatus::getEquipmentId, equipmentIdList));
        Map<String, EquipmentStatus> EquipmentStatusMap = new HashMap<>();
        if(CollUtil.isNotEmpty(equipmentStatusList)){
            EquipmentStatusMap.putAll(equipmentStatusList.stream().collect(Collectors.toMap(EquipmentStatus::getEquipmentId, Function.identity(), (key1, key2) -> key2)));
        }
        //查询设备监测状态
        Map<String, List<ManholeData>> imeiCardNumberMapList = new HashMap<>();
        if(listInDTO.getIsQueryManholeData()){
            List<String> equipmentCodeList = outDTOList.stream().map(EquipmentBaseOutDTO::getEquipmentCode).distinct().collect(Collectors.toList());
            List<ManholeData> manholeDataList = manholeDataMapper.selectList(new LambdaQueryWrapper<ManholeData>()
                    .in(ManholeData::getImeiCardNumber, equipmentCodeList)
                    .orderByDesc(ManholeData::getCreateTime));
            imeiCardNumberMapList.putAll(manholeDataList.stream().collect(Collectors.groupingBy(ManholeData::getImeiCardNumber)));
        }
        List<ManholeData> manholeDataList = null;
        for(EquipmentBaseOutDTO outDTO : outDTOList) {
            EquipmentType equipmentType = equipmentTypeMap.get(outDTO.getEquipmentTypeId());
            if(equipmentType != null){
                outDTO.setEquipmentTypeName(equipmentType.getTypeName());
            }
            EquipmentStatus equipmentStatus = EquipmentStatusMap.get(outDTO.getEquipmentId());
            if(equipmentStatus != null){
                EquipmentStatusOutDTO equipmentStatusOutDTO = BeanUtil.copyProperties(equipmentStatus, EquipmentStatusOutDTO.class);
                outDTO.setEquipmentStatus(equipmentStatusOutDTO);
            }
            if(listInDTO.getIsQueryManholeData()){
                manholeDataList = imeiCardNumberMapList.get(outDTO.getEquipmentCode());
                if(CollUtil.isNotEmpty(manholeDataList)){
                    ManholeData manholeData = manholeDataList.get(0);
                    ManholeDataOutDTO manholeDataOutDTO = BeanUtil.copyProperties(manholeData, ManholeDataOutDTO.class);
                    outDTO.setManholeData(manholeDataOutDTO);
                }
            }
        }
        return outDTOList;
    }

    @Override
    @Transactional
    public boolean updateEquipmentStatus(String equipmentId, Integer currentStatus) {
        EquipmentBase equipment = this.getById(equipmentId);
        if (equipment == null) {
            throw new ServiceException("设备不存在：" + equipmentId);
        }

        LambdaQueryWrapper<EquipmentStatus> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EquipmentStatus::getEquipmentId, equipmentId);
        EquipmentStatus status = equipmentStatusMapper.selectOne(wrapper);

        if (status == null) {
            status = new EquipmentStatus();
            status.setEquipmentId(equipmentId);
            status.setCurrentStatus(currentStatus);
            status.setAlarmStatus(0);
            status.setOnlineStatus(1);
            status.setStatusUpdateTime(LocalDateTime.now());
            return equipmentStatusMapper.insert(status) > 0;
        } else {
            status.setCurrentStatus(currentStatus);
            status.setStatusUpdateTime(LocalDateTime.now());
            return equipmentStatusMapper.updateById(status) > 0;
        }
    }

    @Override
    @Transactional
    public boolean testEquipment(String equipmentId, String testType, String testDetail, String testUser) {
        EquipmentBase equipment = this.getById(equipmentId);
        if (equipment == null) {
            throw new ServiceException("设备不存在：" + equipmentId);
        }

        EquipmentTest test = new EquipmentTest();
        test.setEquipmentId(equipmentId);
        test.setTestType(testType);
        test.setTestResult("SUCCESS");
        test.setTestDetail(testDetail);
        test.setTestTime(LocalDateTime.now());
        test.setTestUser(testUser);
        return equipmentTestMapper.insert(test) > 0;
    }

    @Override
    public Map<String, Object> getEquipmentDetail(String equipmentId) {
        EquipmentBase equipment = this.getById(equipmentId);
        if (equipment == null) {
            throw new ServiceException("设备不存在：" + equipmentId);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("equipmentInfo", equipment);

        if (equipment.getEquipmentTypeId() != null) {
            EquipmentType type = equipmentTypeMapper.selectById(equipment.getEquipmentTypeId());
            result.put("typeInfo", type);
        }

        LambdaQueryWrapper<EquipmentStatus> statusWrapper = new LambdaQueryWrapper<>();
        statusWrapper.eq(EquipmentStatus::getEquipmentId, equipmentId);
        EquipmentStatus status = equipmentStatusMapper.selectOne(statusWrapper);
        result.put("statusInfo", status);

        LambdaQueryWrapper<EquipmentMaintain> maintainWrapper = new LambdaQueryWrapper<>();
        maintainWrapper.eq(EquipmentMaintain::getEquipmentId, equipmentId);
        maintainWrapper.orderByDesc(EquipmentMaintain::getMaintainDate);
        List<EquipmentMaintain> maintainList = equipmentMaintainMapper.selectList(maintainWrapper);
        result.put("maintainList", maintainList);

        LambdaQueryWrapper<EquipmentPointRel> relWrapper = new LambdaQueryWrapper<>();
        relWrapper.eq(EquipmentPointRel::getEquipmentId, equipmentId);
        List<EquipmentPointRel> relList = equipmentPointRelMapper.selectList(relWrapper);
        result.put("pointRelList", relList);

        // 现在 WarningThreshold 有了 equipmentId 字段，直接匹配
        LambdaQueryWrapper<WarningThreshold> thresholdWrapper = new LambdaQueryWrapper<>();
        thresholdWrapper.eq(WarningThreshold::getEquipmentId, equipmentId);
        List<WarningThreshold> thresholdList = warningThresholdMapper.selectList(thresholdWrapper);
        result.put("thresholdList", thresholdList);

        LambdaQueryWrapper<EquipmentTest> testWrapper = new LambdaQueryWrapper<>();
        testWrapper.eq(EquipmentTest::getEquipmentId, equipmentId);
        testWrapper.orderByDesc(EquipmentTest::getTestTime);
        List<EquipmentTest> testList = equipmentTestMapper.selectList(testWrapper);
        result.put("testList", testList);

        return result;
    }

    @Override
    public List<EquipmentBase> getEquipmentByPoint(String pointId) {
        LambdaQueryWrapper<EquipmentPointRel> relWrapper = new LambdaQueryWrapper<>();
        relWrapper.eq(EquipmentPointRel::getPointId, pointId);
        List<EquipmentPointRel> relList = equipmentPointRelMapper.selectList(relWrapper);

        if (relList.isEmpty()) {
            return new ArrayList<>();
        }

        List<String> equipmentIds = relList.stream()
                .map(EquipmentPointRel::getEquipmentId)
                .collect(Collectors.toList());

        return this.listByIds(equipmentIds);
    }
}
