/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.coldchain.modular.monitortarget.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.coldchain.core.alarm.bean.SensorAlarmUser;
import vip.xiaonuo.coldchain.core.config.JfcloudRedisCacheService;
import vip.xiaonuo.coldchain.modular.monitordevice.entity.MonitorDeviceTemplate;
import vip.xiaonuo.coldchain.modular.monitordevice.handler.CustomCellWriteHandler;
import vip.xiaonuo.coldchain.modular.monitordevice.param.MonitorDeviceAddParam;
import vip.xiaonuo.coldchain.modular.monitordevice.service.MonitorDeviceService;
import vip.xiaonuo.coldchain.modular.monitordevicetype.entity.MonitorDeviceType;
import vip.xiaonuo.coldchain.modular.monitortarget.entity.MonitorTarget;
import vip.xiaonuo.coldchain.modular.monitortarget.entity.MonitorTargetTemplate;
import vip.xiaonuo.coldchain.modular.monitortarget.entity.StatusCount;
import vip.xiaonuo.coldchain.modular.monitortarget.enums.MonitorStatusEnum;
import vip.xiaonuo.coldchain.modular.monitortarget.mapper.MonitorTargetMapper;
import vip.xiaonuo.coldchain.modular.monitortarget.param.*;
import vip.xiaonuo.coldchain.modular.monitortarget.service.MonitorTargetService;
import vip.xiaonuo.coldchain.modular.monitortargetregion.entity.MonitorTargetRegion;
import vip.xiaonuo.coldchain.modular.monitortargetregion.service.MonitorTargetRegionService;
import vip.xiaonuo.coldchain.modular.targetroom.entity.TargetRoom;
import vip.xiaonuo.coldchain.modular.targetroom.service.TargetRoomService;
import vip.xiaonuo.common.enums.CommonDeleteFlagEnum;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 监控对象管理Service接口实现类
 *
 * @author 黄渊昊
 * @date 2024/11/13 16:56
 **/
@Service
@Slf4j
public class MonitorTargetServiceImpl extends ServiceImpl<MonitorTargetMapper, MonitorTarget> implements MonitorTargetService {
    @Resource
    private MonitorTargetRegionService monitorTargetRegionService;
    @Resource
    private MonitorDeviceService monitorDeviceService;
    @Resource
    private MonitorTargetMapper monitorTargetMapper;
    @Resource
    private TargetRoomService targetRoomService;
    @Resource
    private JfcloudRedisCacheService jfcloudRedisCacheService;

    @Override
    public Page<MonitorTarget> page(MonitorTargetPageParam monitorTargetPageParam) {
        SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
        QueryWrapper<MonitorTarget> queryWrapper = new QueryWrapper<MonitorTarget>().checkSqlInjection();
        if (StrUtil.isNotBlank(monitorTargetPageParam.getName())) {
            queryWrapper.lambda().like(MonitorTarget::getName, monitorTargetPageParam.getName());
        }
        if (StrUtil.isNotBlank(monitorTargetPageParam.getRoomId())) {
            queryWrapper.lambda().eq(MonitorTarget::getRoomId, monitorTargetPageParam.getRoomId());
        }
        if (ObjectUtil.isAllNotEmpty(monitorTargetPageParam.getSortField(), monitorTargetPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(monitorTargetPageParam.getSortOrder());
            queryWrapper.orderBy(true, monitorTargetPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()), StrUtil.toUnderlineCase(monitorTargetPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(MonitorTarget::getId);
        }
        queryWrapper.lambda().eq(MonitorTarget::getCreateOrg, loginUser.getOrgId()).eq(MonitorTarget::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE);
        Page<MonitorTarget> page = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        //获取设备区域列表并赋值返回
        page.getRecords().forEach(monitorTarget -> {
            monitorTarget.setMonitorTargetRegionList(monitorTargetRegionService.getRegionListByTargetId(monitorTarget.getId()));
            monitorTarget.setRoomName(targetRoomService.queryEntity(monitorTarget.getRoomId()).getName());
        });
        return page;
    }

    @Override
    public Page<MonitorTarget> pageWithRoom(MonitorTargetPageParam monitorTargetPageParam) {
        SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
        QueryWrapper<MonitorTarget> queryWrapper = new QueryWrapper<MonitorTarget>().checkSqlInjection();
        if (ObjectUtil.isNotEmpty(monitorTargetPageParam.getName())) {
            queryWrapper.lambda().like(MonitorTarget::getName, monitorTargetPageParam.getName());
        }
        if (ObjectUtil.isAllNotEmpty(monitorTargetPageParam.getSortField(), monitorTargetPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(monitorTargetPageParam.getSortOrder());
            queryWrapper.orderBy(true, monitorTargetPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()), StrUtil.toUnderlineCase(monitorTargetPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(MonitorTarget::getId);
        }
        queryWrapper.lambda().eq(MonitorTarget::getCreateOrg, loginUser.getOrgId()).eq(MonitorTarget::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE);
        Page<MonitorTarget> page = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        //获取设备区域列表并赋值返回
        page.getRecords().forEach(monitorTarget -> {
            monitorTarget.setMonitorTargetRegionList(monitorTargetRegionService.getRegionListByTargetId(monitorTarget.getId()));
            monitorTarget.setCreateOrgName(loginUser.getOrgName());
            monitorTarget.setRoomName(targetRoomService.queryEntity(monitorTarget.getRoomId()).getName());
        });
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(MonitorTargetAddParam monitorTargetAddParam) {
        MonitorTarget monitorTarget = BeanUtil.toBean(monitorTargetAddParam, MonitorTarget.class);
        this.save(monitorTarget);
        
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(MonitorTargetEditParam monitorTargetEditParam) {
        MonitorTarget monitorTarget = this.queryEntity(monitorTargetEditParam.getId());
        BeanUtil.copyProperties(monitorTargetEditParam, monitorTarget);
        this.updateById(monitorTarget);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchEdit(MonitorTargetBatchEditWithRoomParam batchEditWithRoomParam) {
        List<MonitorTarget> monitorTargetList = new ArrayList<>();
        batchEditWithRoomParam.getIdList().forEach(id -> {
            MonitorTarget monitorTarget = this.queryEntity(id);
            BeanUtil.copyProperties(batchEditWithRoomParam, monitorTarget);
            monitorTargetList.add(monitorTarget);
        });
        this.updateBatchById(monitorTargetList);
    }

    @Override
    public List<MonitorTarget> getTargetListByRoom(String roomId) {
        LambdaQueryWrapper<MonitorTarget> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MonitorTarget::getRoomId,roomId).eq(MonitorTarget::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE);
        return list(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addWithRoom(MonitorTargetAddWithRoomParam monitorTargetAddWithRoomParam) {
        MonitorTarget monitorTarget = BeanUtil.toBean(monitorTargetAddWithRoomParam, MonitorTarget.class);
        this.save(monitorTarget);
        
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void editWithRoom(MonitorTargetEditWithRoomParam monitorTargetEditWithRoomParam) {
        MonitorTarget monitorTarget = this.queryEntity(monitorTargetEditWithRoomParam.getId());
        BeanUtil.copyProperties(monitorTargetEditWithRoomParam, monitorTarget);
        this.updateById(monitorTarget);
        
    }

    @Override
    public TargetRoom getRoomByMonitorTargetId(String monitorTargetId) {
        if (Objects.nonNull(monitorTargetId)) {
            MonitorTarget monitorTarget = this.getById(monitorTargetId);
            if (Objects.nonNull(monitorTarget)) {
                String roomId = monitorTarget.getRoomId();
                return targetRoomService.getById(roomId);
            }
        }
        return null;
    }

    /**
     * 批量更新离线设备
     * @param allSensorCodes
     */
    @Override
    public void updateStatusbatch(Set<String> allSensorCodes) {
        // 构建查询建大仁科条件
        LambdaQueryWrapper<MonitorTargetRegion> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(MonitorTargetRegion::getModelName, "RS");
        queryWrapper.in(MonitorTargetRegion::getSensorCode,allSensorCodes);
        queryWrapper.eq(MonitorTargetRegion::getDeleteFlag,CommonDeleteFlagEnum.NOT_DELETE);
        List<MonitorTargetRegion> targetRegions = monitorTargetRegionService.list(queryWrapper);
        Set<String> monitorTargetIds = targetRegions.stream()
                .filter(monitorTargetRegion -> monitorTargetRegion.getDeviceCode() != null)
                .map(MonitorTargetRegion::getMonitorTargetId)
                .collect(Collectors.toSet());
        // 批量更新状态
        if (!monitorTargetIds.isEmpty()) {
            LambdaUpdateWrapper<MonitorTarget> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(MonitorTarget::getId, monitorTargetIds);
            updateWrapper.set(MonitorTarget::getStatus, MonitorStatusEnum.OFF.getCode());
            // 执行批量更新
            boolean updateResult = this.update(updateWrapper);
            if (updateResult) {
                log.info("批量更新成功，已将 {} 条记录状态修改为 OFF", monitorTargetIds.size());
            } else {
                log.warn("批量更新失败，无法更新状态为 OFF 的记录");
            }
        } else {
            log.info("未找到符合条件的 monitorTargetId，无需更新");
        }
    }

    @Override
//    @Cacheable(value = JfcloudColdChainConstants.MONITORTARGET_CACHE_NAME,
//            key = "#monitorTargetPageParam.orgId",
//            unless = "#result == null")
    public Page<MonitorTarget> selectMonitorTargetByPage(MonitorTargetPageParam monitorTargetPageParam) {
        if (StrUtil.isBlank(monitorTargetPageParam.getOrgId())) {
            monitorTargetPageParam.setOrgId(StpLoginUserUtil.getLoginUser().getOrgId());
        }
        Page<MonitorTarget> page = new Page<>(monitorTargetPageParam.getCurrent(), monitorTargetPageParam.getSize());
        Page<MonitorTarget> monitorTargetPage = (Page<MonitorTarget>) monitorTargetMapper.selectMonitorTargetByPage(page, monitorTargetPageParam);
        monitorTargetPage.getRecords().forEach(monitorTarget -> {
            monitorTarget.setRoomName(targetRoomService.getById(monitorTarget.getRoomId()).getName());
        });
        return monitorTargetPage;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<MonitorTargetIdParam> monitorTargetIdParamList) {
        for (MonitorTargetIdParam monitorTargetIdParam : monitorTargetIdParamList) {
            List<MonitorTargetRegion> regionList = monitorTargetRegionService.getRegionListByTargetId(monitorTargetIdParam.getId());
            if (!regionList.isEmpty()) {
                throw new CommonException("监控对象下仍存在分区，无法删除！");
            }
        }
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(monitorTargetIdParamList, MonitorTargetIdParam::getId));
    }

    @Override
    public MonitorTarget detail(MonitorTargetIdParam monitorTargetIdParam) {
        return this.queryEntity(monitorTargetIdParam.getId());
    }

    @Override
    public MonitorTarget queryEntity(String id) {
        MonitorTarget monitorTarget = this.getById(id);
        if (ObjectUtil.isEmpty(monitorTarget)) {
            throw new CommonException("监控对象管理不存在，id值为：{}", id);
        }
        return monitorTarget;
    }

    @Override
    public List<MonitorTarget> getListByUser(String userId) {
        LambdaQueryWrapper<MonitorTarget> queryWrapper = new LambdaQueryWrapper<MonitorTarget>();
        if (ObjectUtil.isNotNull(userId)) {
            queryWrapper.eq(MonitorTarget::getCreateUser, userId).orderByDesc(MonitorTarget::getCreateTime);
        } else {
            queryWrapper.eq(MonitorTarget::getCreateUser, StpLoginUserUtil.getLoginUser().getId());
        }
        queryWrapper.eq(MonitorTarget::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE).orderByDesc(MonitorTarget::getCreateTime);
        List<MonitorTarget> monitorTargetList = list(queryWrapper);
        monitorTargetList.forEach(monitorTarget -> {
            monitorTarget.setMonitorTargetRegionList(monitorTargetRegionService.getRegionListByTargetId(monitorTarget.getId()));
        });
        return monitorTargetList;
    }


    /**
     * jackzhou 重写 2025-1-7 新方法 selectMonitorTargetByPage
     * @param monitorTargetPageParam
     * @return
     */
    @Deprecated
    @Override
    public Page<MonitorTarget> getPageByUser(MonitorTargetPageParam monitorTargetPageParam) {
        QueryWrapper<MonitorTarget> queryWrapper = new QueryWrapper<MonitorTarget>().checkSqlInjection();
        if (StrUtil.isNotBlank(monitorTargetPageParam.getName())) {
            queryWrapper.lambda().like(MonitorTarget::getName, monitorTargetPageParam.getName());
        }
        if (StrUtil.isNotBlank(monitorTargetPageParam.getUserId())) {
            queryWrapper.lambda().eq(MonitorTarget::getCreateUser, monitorTargetPageParam.getUserId());
        }
        if (StrUtil.isNotBlank(monitorTargetPageParam.getRoomId())) {
            queryWrapper.lambda().eq(MonitorTarget::getRoomId, monitorTargetPageParam.getRoomId());
        }
        if (StrUtil.isBlank(monitorTargetPageParam.getOrgId())) {
            queryWrapper.lambda().eq(MonitorTarget::getCreateOrg, StpLoginUserUtil.getLoginUser().getOrgId());
        } else {
            queryWrapper.lambda().eq(MonitorTarget::getCreateOrg, monitorTargetPageParam.getOrgId());
        }
        if (ObjectUtil.isAllNotEmpty(monitorTargetPageParam.getSortField(), monitorTargetPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(monitorTargetPageParam.getSortOrder());
            queryWrapper.orderBy(true, monitorTargetPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()), StrUtil.toUnderlineCase(monitorTargetPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(MonitorTarget::getStatus).orderByAsc(MonitorTarget::getName);
        }
        queryWrapper.lambda().eq(MonitorTarget::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE);
        Page<MonitorTarget> page1 = new Page<>(monitorTargetPageParam.getCurrent(), monitorTargetPageParam.getSize());
        Page<MonitorTarget> rlt = this.page(page1, queryWrapper);
        //获取设备区域列表并赋值返回
        rlt.getRecords().forEach(monitorTarget -> {
            monitorTarget.setMonitorTargetRegionList(monitorTargetRegionService.getRegionListByTargetId(monitorTarget.getId()));
            monitorTarget.setRoomName(targetRoomService.queryEntity(monitorTarget.getRoomId()).getName());
        });
        return rlt;

    }

    @Override
    public TargetStatus getTargetCount(String name, String roomId) {
        SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
        List<StatusCount> countByStatusList = monitorTargetMapper.getCountByStatus(name, roomId, loginUser.getOrgId());
        Long total = 0L;
        Long online = 0L;
        Long offline = 0L;
        for (StatusCount statusCount : countByStatusList) {
            if (statusCount.getStatus().equals("1")) {
                online = statusCount.getCount();
            } else {
                offline = statusCount.getCount();
            }
        }
        total = online + offline;
        return new TargetStatus(total, online, offline);
    }

    @Override
    public boolean updateLastHeartbeatTimeByDeviceId(Integer deviceId, Date timestamp) {
        Assert.notNull(deviceId, "deviceId cannot be null");
//        MonitorDevice monitorDevice = monitorDeviceService.queryByDeviceCode(deviceId);
//        MonitorDevice monitorDevice = monitorDeviceService.queryEntity(deviceId.toString());
        List<String> targetIdList = monitorTargetRegionService.getTargetIdListByDeviceId(String.valueOf(deviceId));
        if (ObjectUtil.isEmpty(targetIdList)) {
            return false;
        }
        List<MonitorTarget> monitorTargetList = new ArrayList<>();
        for (String targetId : targetIdList) {
            MonitorTarget monitorTarget = queryEntity(targetId);
            monitorTarget.setLastHeartbeatTime(timestamp);
            monitorTargetList.add(monitorTarget);
        }
        return updateBatchById(monitorTargetList);
    }

    @Override
    public boolean updateLastLoginTimeByDeviceId(Integer deviceId, Date timestamp) {
//        MonitorDevice monitorDevice = monitorDeviceService.queryEntity(deviceId.toString());
        List<String> targetIdList = monitorTargetRegionService.getTargetIdListByDeviceId(String.valueOf(deviceId));
        if (ObjectUtil.isEmpty(targetIdList)) {
            return false;
        }
        List<MonitorTarget> monitorTargetList = new ArrayList<>();
        for (String targetId : targetIdList) {
            MonitorTarget monitorTarget = queryEntity(targetId);
            monitorTarget.setLastLoginTime(timestamp);
            monitorTargetList.add(monitorTarget);
        }
        return updateBatchById(monitorTargetList);
    }

    @Override
    public boolean updateStatusByDeviceCode(String deviceCode, Integer route, MonitorStatusEnum monitorStatusEnum) {
        MonitorTargetRegion oneByDeviceCodeAndSensorNo = monitorTargetRegionService.findOneByDeviceCodeAndSensorNo(deviceCode, route);
        if (Objects.nonNull(oneByDeviceCodeAndSensorNo)) {
            String monitorTargetId = oneByDeviceCodeAndSensorNo.getMonitorTargetId();
            if (StrUtil.isNotBlank(monitorTargetId)) {
                MonitorTarget monitorTarget = this.getById(monitorTargetId);
                if (Objects.nonNull(monitorTarget)) {
                    monitorTarget.setStatus(monitorStatusEnum.getCode());
                    
                    return this.updateById(monitorTarget);
                }
            }
        }
        return false;
    }

    @Override
    public List<MonitorTarget> myList(Boolean isAll) {
        SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
        LambdaQueryWrapper<MonitorTarget> queryWrapper = new LambdaQueryWrapper<>();
        if (!isAll) {
            queryWrapper.eq(MonitorTarget::getStatus, MonitorStatusEnum.ONLINE.getCode())
                    .orderByDesc(MonitorTarget::getCreateTime);
        }
        queryWrapper.eq(MonitorTarget::getCreateOrg, loginUser.getOrgId()).eq(MonitorTarget::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE);
        return list(queryWrapper);
    }

    @Override
    public void downloadTemplate(HttpServletResponse response) {
        String fileName = "冰箱导入模板";
        String sheetName = "冰箱设备导入模板";
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + URLEncoder.encode(fileName, StandardCharsets.UTF_8) + ".xls");
        //模板实体类
        List<MonitorDeviceTemplate> secondInspProbExcelDTOS = new ArrayList<>();
        //普通下拉数据
        Map<Integer, String[]> map = ordinarySelect();
        try (OutputStream outputStream = response.getOutputStream()) {
            EasyExcel.write(outputStream, MonitorTargetTemplate.class)
                    .registerWriteHandler(new CustomCellWriteHandler(map))
                    .excelType(ExcelTypeEnum.XLS)
                    .sheet(sheetName)
                    .doWrite(secondInspProbExcelDTOS);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 普通下拉数据
     *
     * @return
     */
    private Map<Integer, String[]> ordinarySelect() {
        Map<Integer, String[]> map = new HashMap<>();

        List<TargetRoom> list = targetRoomService.myList();
        List<String> billingNameList = list.stream().map(TargetRoom::getName).toList();
        map.put(0, billingNameList.toArray(new String[0]));
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importMonitorDevice(MultipartFile file) {
        List<MonitorTargetTemplate> monitorTargetTemplates = null;
        // excel同步读取数据
        try {
            monitorTargetTemplates = EasyExcel.read(new BufferedInputStream(file.getInputStream())).head(MonitorTargetTemplate.class).sheet().doReadSync();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 检查是否大于1000条
        if (monitorTargetTemplates.size() > 1000) {
            throw new RuntimeException("超过最多处理条数");
        }
        List<MonitorTargetAddWithRoomParam> monitorTargetAddParamList = new ArrayList<>();
        for (MonitorTargetTemplate monitorTargetTemplate : monitorTargetTemplates) {
            if (StrUtil.isBlank(monitorTargetTemplate.getName()) && StrUtil.isBlank(monitorTargetTemplate.getRoomName())) {
                throw new CommonException("冰箱：*" + monitorTargetTemplate.getName() + "*包含未填的必填项");
            }
            MonitorTargetAddWithRoomParam monitorTargetAddParam = BeanUtil.copyProperties(monitorTargetTemplate, MonitorTargetAddWithRoomParam.class);
            TargetRoom roomByName = targetRoomService.getRoomByName(monitorTargetTemplate.getRoomName());
            monitorTargetAddParam.setRoomId(roomByName.getId());
            monitorTargetAddParamList.add(monitorTargetAddParam);
        }
        // 入库操作
        monitorTargetAddParamList.forEach(this::addWithRoom);
    }
}
