package cn.hanghui.outapi.platform.tenant.service.impl;

import cn.hanghui.outapi.platform.alipay.entity.rest.request.AlipayAppAuthCancelledMqRequest;
import cn.hanghui.outapi.platform.common.entity.po.Account;
import cn.hanghui.outapi.platform.common.entity.po.AccountAuthConfig;
import cn.hanghui.outapi.platform.common.entity.rest.RestResult;
import cn.hanghui.outapi.platform.common.exception.BusinessException;
import cn.hanghui.outapi.platform.common.mapper.AccountAuthConfigMapper;
import cn.hanghui.outapi.platform.common.service.BaseService;
import cn.hanghui.outapi.platform.common.utils.ClassUtil;
import cn.hanghui.outapi.platform.common.utils.Preconditions;
import cn.hanghui.outapi.platform.tenant.entity.dto.*;
import cn.hanghui.outapi.platform.tenant.entity.dto.ampe.AmpeDeviceDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.ampe.HhFaceDeviceDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.ampe.HhFaceDeviceSearch;
import cn.hanghui.outapi.platform.tenant.entity.enums.*;
import cn.hanghui.outapi.platform.tenant.entity.po.*;
import cn.hanghui.outapi.platform.tenant.mapper.*;
import cn.hanghui.outapi.platform.tenant.service.TenantService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author shisl
 * @package cn.hanghui.outapi.platform.tenant.service.impl
 * @class TenantServiceImpl
 * @date 2023/4/18 下午2:17
 * @description
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TenantServiceImpl extends BaseService implements TenantService {
    private final TenantMapper tenantMapper;
    private final DeviceMapper deviceMapper;
    private final SceneMapper sceneMapper;
    private final UserLibMapper userLibMapper;
    private final PurchaserMapper purchaserMapper;
    private final ApplicationTypeMapper applicationTypeMapper;
    private final DeviceModelMapper deviceModelMapper;
    private final CommonImpl commonImpl;
    private final AccountAuthConfigMapper accountAuthConfigMapper;

    @Override
    public RestResult<List<TenantVo>> list(TenantDto dto) {
        List<Device> devices = deviceMapper.selectList(Wrappers.lambdaQuery(Device.class).eq(Device::getStatus, Boolean.TRUE).isNotNull(Device::getTenantId).eq(Device::getSn, dto.getSn()).eq(Device::getIsDeleted, Boolean.FALSE));
        if (devices == null || devices.size() == 0) {
            return RestResult.error("设备商户平台未授权");
        }
        List<Long> tenantIds = devices.stream().filter(item -> item.getTenantId() != null).map(Device::getTenantId).collect(Collectors.toList());
        LambdaQueryWrapper<Tenant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tenant::getIsDeleted, Boolean.FALSE);
        if (tenantIds != null && tenantIds.size() > 0) {
            wrapper.in(Tenant::getId, tenantIds);
        }
        List<Tenant> list = tenantMapper.selectList(wrapper);
        List<TenantVo> vos = BeanUtil.copyToList(list, TenantVo.class);
        return RestResult.ok(vos != null ? completeOthers(devices, vos) : Collections.emptyList());
    }

    private List<TenantVo> completeOthers(List<Device> devices, List<TenantVo> vos) {
        List<Long> sceneIds = devices.stream().filter(item -> item.getSceneId() != null).map(Device::getSceneId).collect(Collectors.toList());
        List<Scene> scenelist = new ArrayList<>();
        List<UserLib> userliblist = new ArrayList<>();
        if (sceneIds != null && sceneIds.size() > 0) {
            LambdaQueryWrapper<Scene> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Scene::getIsDeleted, Boolean.FALSE);
            wrapper.in(Scene::getId, sceneIds);
            scenelist = sceneMapper.selectList(wrapper);
        }
        List<Long> userLibIds = devices.stream().filter(item -> item.getUserLibId() != null).map(Device::getUserLibId).collect(Collectors.toList());
        if (userLibIds != null && userLibIds.size() > 0) {
            LambdaQueryWrapper<UserLib> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserLib::getIsDeleted, Boolean.FALSE);
            wrapper.in(UserLib::getId, userLibIds);
            userliblist = userLibMapper.selectList(wrapper);
        }
        Map<Long, Device> deviceMap = devices.stream().collect(Collectors.toMap(Device::getTenantId, a -> a, (k1, k2) -> k1));
        Map<Long, Scene> sceneMap = scenelist.stream().collect(Collectors.toMap(Scene::getId, a -> a, (k1, k2) -> k1));
        Map<Long, UserLib> userLibMap = userliblist.stream().collect(Collectors.toMap(UserLib::getId, a -> a, (k1, k2) -> k1));
        vos.stream().forEach(item -> {
            Device device = deviceMap.get(item.getId());
            if (device != null) {
                item.setMode(device.getMode());
                if (device.getSceneId() != null) {
                    item.setSceneId(device.getSceneId());
                    Scene scene = sceneMap.get(device.getSceneId());
                    if (scene != null) {
                        item.setSceneName(scene.getSceneName());
                        item.setTrade(scene.getTrade());
                    }
                }
                if (device.getUserLibId() != null) {
                    item.setUserLibId(device.getUserLibId());
                    UserLib userLib = userLibMap.get(device.getUserLibId());
                    if (userLib != null) {
                        item.setUserLibName(userLib.getUserLibName());
                        item.setGroupId(userLib.getGroupId());
                        if (StrUtil.isNotBlank(device.getMode()) && "elasticity".equals(device.getMode())) {
                            //弹性模式
                            item.setLogicGroupID(userLib.getGroupId());
                        }
                    }
                }
                //处理设备相关参数
                handTenantDeviceParams(item, device);

                //购买方
                Purchaser purchaser = purchaserMapper.selectById(device.getPurchaserId());
                if (ObjectUtil.isNotNull(purchaser)) {
                    item.setCompanyName(purchaser.getCompanyName());
                }
                //应用类型
                ApplicationType applicationType = applicationTypeMapper.selectById(device.getApplicationTypeId());
                if (ObjectUtil.isNotNull(applicationType)) {
                    item.setApplicationType(applicationType.getApplicationType());
                }
                //设备类型（硬件）
                DeviceModel deviceModelHardware = deviceModelMapper.selectById(device.getDeviceModelHardwareId());
                if (ObjectUtil.isNotNull(deviceModelHardware)) {
                    item.setDeviceModelHardware(deviceModelHardware.getDeviceModel());
                }
                //设备类型（环境）
                DeviceModel deviceModelEnvironment = deviceModelMapper.selectById(device.getDeviceModelEnvironmentId());
                if (ObjectUtil.isNotNull(deviceModelEnvironment)) {
                    item.setDeviceModelEnvironment(deviceModelEnvironment.getDeviceModel());
                }
                //系统类型
                SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(device.getSystemTypeCode());
                if (ObjectUtil.isNotNull(systemTypeEnum)) {
                    item.setSystemType(systemTypeEnum.getDesc());
                }
            }
        });
        return vos;
    }

    private void handTenantDeviceParams(TenantVo item, Device device) {
        BeanUtil.copyProperties(device, item, "id");
        //TODO 20230921添加参数
        item.setUseAlipayFace(device.getUseAlipayFace() != null ? device.getUseAlipayFace() : DeviceDefaultParam.defaultUseAlipayFace);
        item.setLinkageAds(device.getLinkageAds() != null ? device.getLinkageAds() : DeviceDefaultParam.defaultLinkageAds);
        item.setSuccessPageTime(device.getSuccessPageTime() != null ? device.getSuccessPageTime() : DeviceDefaultParam.defaultSuccessPageTime);
        item.setFailPageTime(device.getFailPageTime() != null ? device.getFailPageTime() : DeviceDefaultParam.defaultFailPageTime);
        item.setZoloConfig(device.getZoloConfig() != null ? device.getZoloConfig() : DeviceDefaultParam.initZoloConfig());
        item.setUseIdcard(device.getUseIdcard() != null ? device.getUseIdcard() : DeviceDefaultParam.defaultUseIdcard);
        item.setUsePersonCard(device.getUsePersonCard() != null ? device.getUsePersonCard() : DeviceDefaultParam.defaultUsePersonCard);
        item.setUseQrcode(device.getUseQrcode() != null ? device.getUseQrcode() : DeviceDefaultParam.defaultUseQrcode);
        item.setUseLinkage(device.getUseLinkage() != null ? device.getUseLinkage() : DeviceDefaultParam.defaultUseLinkage);
        item.setFaceMode(device.getFaceMode() != null ? device.getFaceMode() : DeviceDefaultParam.defaultFaceMode);
        item.setClickButtonText(device.getClickButtonText() != null ? device.getClickButtonText() : DeviceDefaultParam.defaultClickButtonText);
        item.setIsCaptureFace(device.getIsCaptureFace() != null ? device.getIsCaptureFace() : DeviceDefaultParam.defaultIsCaptureFace);
        item.setIsNeed1V1(device.getIsNeed1V1() != null ? device.getIsNeed1V1() : DeviceDefaultParam.defaultIsNeed1V1);
        item.setUseSerialPort(device.getUseSerialPort() != null ? device.getUseSerialPort() : DeviceDefaultParam.defaultUseSerialPort);
        item.setSignalNo(device.getSignalNo());
        item.setLightMode(device.getLightMode() != null ? device.getLightMode() : DeviceDefaultParam.defaultLightMode);
        item.setVolume(device.getVolume() != null ? device.getVolume() : DeviceDefaultParam.defaultVolume);
        item.setSucVoice(device.getSucVoice() != null ? device.getSucVoice() : DeviceDefaultParam.defaultSucVoice);
        item.setSucText(device.getSucText() != null ? device.getSucText() : DeviceDefaultParam.defaultSucText);
        item.setFailVoice(device.getFailVoice() != null ? device.getFailVoice() : DeviceDefaultParam.defaultFailVoice);
        item.setFailText(device.getFailText() != null ? device.getFailText() : DeviceDefaultParam.defaultFailText);
        item.setHideNavigationBar(device.getHideNavigationBar() != null ? device.getHideNavigationBar() : DeviceDefaultParam.defaultHideNavigationBar);
        item.setForbidPullDown(device.getForbidPullDown() != null ? device.getForbidPullDown() : DeviceDefaultParam.defaultForbidPullDown);
        item.setHomePageUrl(device.getHomePageUrl() != null ? device.getHomePageUrl() : DeviceDefaultParam.defaultHomePageUrl);
        item.setTransitionPageUrl(device.getTransitionPageUrl() != null ? device.getTransitionPageUrl() : DeviceDefaultParam.defaultTransitionPageUrl);
        //TODO 20231007添加参数
        item.setHeartTrackingUrl(device.getHeartTrackingUrl() != null ? device.getHeartTrackingUrl() : DeviceDefaultParam.defaultHeartTrackingUrl);
        item.setTransitPushUrl(device.getTransitPushUrl() != null ? device.getTransitPushUrl() : DeviceDefaultParam.defaultTransitPushUrl);
        item.setShowTopBar(device.getShowTopBar() != null ? device.getShowTopBar() : DeviceDefaultParam.defaultShowTopBar);
        item.setLeftTopBarText(device.getLeftTopBarText() != null ? device.getLeftTopBarText() : DeviceDefaultParam.defaultLeftTopBarText);
        item.setRightTopBarText(device.getRightTopBarText() != null ? device.getRightTopBarText() : DeviceDefaultParam.defaultRightTopBarText);
        //TODO 20231019添加参数
        item.setPassWay(device.getPassWay() != null ? device.getPassWay() : DeviceDefaultParam.defaultPassWay);
        //TODO 20231110添加参数
        item.setIsOpenAgeLimit(device.getIsOpenAgeLimit() != null ? device.getIsOpenAgeLimit() : DeviceDefaultParam.defaultIsOpenAgeLimit);
        item.setLimitSectionStart(device.getLimitSectionStart());
        item.setLimitSectionEnd(device.getLimitSectionEnd());
        item.setAgeForbidText(device.getAgeForbidText() != null ? device.getAgeForbidText() : DeviceDefaultParam.defaultAgeForbidText);
        item.setMpassword(device.getMpassword() != null ? device.getMpassword() : DeviceDefaultParam.defaultMpassword);
        //TODO 20231128添加参数
        item.setIsOpenPassport(device.getIsOpenPassport() != null ? device.getIsOpenPassport() : DeviceDefaultParam.isOpenPassport);
        item.setIsPushGM(device.getIsPushGM() != null ? device.getIsPushGM() : DeviceDefaultParam.isPushGM);
        item.setGMAddress(device.getGMAddress() != null ? device.getGMAddress() : DeviceDefaultParam.GMAddress);
        item.setGMFrequency(device.getGMFrequency() != null ? device.getGMFrequency() : DeviceDefaultParam.GMFrequency);
        item.setAutoLaunch(device.getAutoLaunch() != null ? device.getAutoLaunch() : DeviceDefaultParam.autoLaunch);
        //TODO 20231215添加参数
        item.setUseEntryDetector(device.getUseEntryDetector() != null ? device.getUseEntryDetector() : DeviceDefaultParam.useEntryDetector);
        //TODO 20240103添加参数
        item.setLogPushUrl(device.getLogPushUrl() != null ? device.getLogPushUrl() : DeviceDefaultParam.defaultLogPushUrl);
        item.setCameraType(device.getCameraType() != null ? device.getCameraType() : DeviceDefaultParam.cameraType);
        item.setCameraBrand(device.getCameraBrand() != null ? device.getCameraBrand() : DeviceDefaultParam.cameraBrand);
        //TODO 20240105添加参数
        item.setEntryFaceMode(StrUtil.isNotBlank(device.getEntryFaceMode()) ? device.getEntryFaceMode() : DeviceDefaultParam.entryFaceMode);
        //TODO 20240228添加参数
        item.setUserOutputMode(StrUtil.isNotBlank(device.getUserOutputMode()) ? device.getUserOutputMode() : DeviceDefaultParam.defaultUserOutputMode);
        item.setIdCardReaderBrand(Preconditions.isNotBlank(device.getIdCardReaderBrand()) ? device.getIdCardReaderBrand() : DeviceDefaultParam.defaultIdCardReaderBrand);
        //TODO 20240315添加参数
        item.setAuthVerifiedFacein(Preconditions.isNotBlank(device.getAuthVerifiedFacein()) ? device.getAuthVerifiedFacein() : Boolean.FALSE);
        item.setManualInIdCard(Preconditions.isNotBlank(device.getManualInIdCard()) ? device.getManualInIdCard() : Boolean.FALSE);
        item.setManualInIdCardAuth(Preconditions.isNotBlank(device.getManualInIdCard()) && device.getManualInIdCard() ? device.getManualInIdCardAuth() : null);
        //TODO 20240327添加参数
        item.setLinkageCheckMode((!device.getUseLinkage() || LinkageCheckModeEnum.getEnumByCode(device.getLinkageCheckMode()) == null) ? DeviceDefaultParam.defaultLinkageCheckMode : device.getLinkageCheckMode());
        item.setResultPageTemplate(ResultPageTemplateEnum.getEnumByCode(device.getResultPageTemplate()) != null ? device.getResultPageTemplate() : DeviceDefaultParam.defaultResultPageTemplate);
        //TODO 20240423添加参数
        item.setRelayOpenModel(device.getRelayOpenModel());
        item.setOpenCloseInterval(device.getOpenCloseInterval() == null ? DeviceDefaultParam.defaultOpenCloseInterval : device.getOpenCloseInterval());
        item.setSignalInterval(device.getSignalInterval() == null ? DeviceDefaultParam.defaultSignalInterval : device.getSignalInterval());
        item.setGateTimeOut(device.getGateTimeOut() == null ? DeviceDefaultParam.defaultGateTimeOut : device.getGateTimeOut());
        item.setAnalysisPhoto(device.getAnalysisPhoto() == null ? DeviceDefaultParam.defaultAnalysisPhoto : device.getAnalysisPhoto());
        item.setAnalysisFingerprint(device.getAnalysisFingerprint() == null ? DeviceDefaultParam.defaultAnalysisFingerprint : device.getAnalysisFingerprint());
        //TODO 20240506添加参数
        item.setIdCardInterval(device.getIdCardInterval() == null ? DeviceDefaultParam.defaultIdCardInterval : device.getIdCardInterval());
        //TODO 20240520添加参数
        item.setCommunicationMode(device.getCommunicationMode());
        item.setWsAddress(device.getWsAddress());
        item.setCommunicationSerialPort(device.getCommunicationSerialPort());
        item.setDoorSerialPort(device.getDoorSerialPort());
        //联动平台超时时间
        item.setLinkTimeout(device.getLinkTimeout());
        //todo 系统类型
        item.setSystemTypeCode(device.getSystemTypeCode());
        //todo 20240604
        item.setAnonymousStorage(device.getAnonymousStorage() == null ? DeviceDefaultParam.defaultAnonymousStorage : device.getAnonymousStorage());
        item.setCompareSilentDisplay(device.getCompareSilentDisplay() == null ? DeviceDefaultParam.defaultCompareSilentDisplay : device.getCompareSilentDisplay());
        item.setCompareSilentDisplayTime(device.getCompareSilentDisplayTime() == null ? DeviceDefaultParam.defaultCompareSilentDisplayTime : device.getCompareSilentDisplayTime());
        item.setCompareTopTitle(device.getCompareTopTitle());
        item.setOpenDelayTime(device.getOpenDelayTime());
        //todo 20240807
        item.setLedBrightness(device.getLedBrightness());
        //todo 20240819
        item.setVerifyRetryTimes(device.getVerifyRetryTimes());
        item.setVerifyLinkTimeout(device.getVerifyLinkTimeout());
        item.setScheduledRestart(device.getScheduledRestart());
        item.setScheduledRestartTime(device.getScheduledRestartTime());
        //todo 20240822
        item.setIc14443IcCardFunction(device.getIc14443IcCardFunction());
        item.setIc14443ReaderBrand(device.getIc14443ReaderBrand());
        item.setIc14443ReaderSectorNumbers(device.getIc14443ReaderSectorNumbers());
        item.setIc14443ReaderBlock(device.getIc14443ReaderBlock());
        item.setIc14443ReaderKey(device.getIc14443ReaderKey());
        item.setIc14443StartOffset(device.getIc14443StartOffset());
        item.setIc14443EndOffset(device.getIc14443EndOffset());
        item.setIc14443PersonCardComparison(device.getIc14443PersonCardComparison());
        item.setIc14443SameCardIntervalTime(device.getIc14443SameCardIntervalTime());
        item.setIc15693IcCardFunction(device.getIc15693IcCardFunction());
        item.setIc15693ReaderBrand(device.getIc15693ReaderBrand());
        item.setIc15693ReaderBlock(device.getIc15693ReaderBlock());
        item.setIc15693StartOffset(device.getIc15693StartOffset());
        item.setIc15693EndOffset(device.getIc15693EndOffset());
        item.setIc15693PersonCardComparison(device.getIc15693PersonCardComparison());
        item.setIc15693SameCardIntervalTime(device.getIc15693SameCardIntervalTime());
        //todo 20240822
        item.setExpirationDate(device.getExpirationDate());
        //兜底手动输入手动输入证件号
        if (ObjectUtil.isNull(item.getManualInIdCardAuth())) {
            ManualInIdCardAuthDto manualInIdCardAuth = new ManualInIdCardAuthDto();
            manualInIdCardAuth.setAppId("");
            manualInIdCardAuth.setAppKey("");
            manualInIdCardAuth.setAppSecret("");
            manualInIdCardAuth.setPrivateKey("");
            item.setManualInIdCardAuth(manualInIdCardAuth);
        }

    }

    @Override
    public RestResult innerList() {
        List<Tenant> list = tenantMapper.selectList(Wrappers.lambdaQuery(Tenant.class).eq(Tenant::getIsDeleted, Boolean.FALSE));
        List<TenantVo> vos = BeanUtil.copyToList(list, TenantVo.class);
        return RestResult.ok(vos != null ? vos : Collections.emptyList());
    }

    @Override
    public RestResult<List<TenantVo>> innerList(Account account) {
        List<Long> tenantIds = commonImpl.getAmpeTenantIds(account);
        if (Preconditions.isBlank(tenantIds)) {
            return RestResult.ok(Collections.emptyList());
        }
        List<Tenant> list = tenantMapper.selectList(Wrappers.lambdaQuery(Tenant.class).in(Tenant::getId, tenantIds).eq(Tenant::getIsDeleted, Boolean.FALSE));
        List<TenantVo> vos = BeanUtil.copyToList(list, TenantVo.class);
        return RestResult.ok(vos != null ? vos : Collections.emptyList());
    }

    @Override
    public RestResult<List<TenantVo>> getAuthTenantList(Account account, AuthModuleTypeEnum authModuleTypeEnum) {
        List<Long> tenantIds = commonImpl.getAuthModuleIds(account, authModuleTypeEnum);
        if (Preconditions.isBlank(tenantIds)) {
            return RestResult.ok(Collections.emptyList());
        }
        List<Tenant> list = tenantMapper.selectList(Wrappers.lambdaQuery(Tenant.class).in(Tenant::getId, tenantIds).eq(Tenant::getIsDeleted, Boolean.FALSE));
        List<TenantVo> vos = BeanUtil.copyToList(list, TenantVo.class);
        return RestResult.ok(vos != null ? vos : Collections.emptyList());
    }

    @Override
    public RestResult<IPage<DeviceVo>> page(HhFaceDeviceSearch dto, Account account) {
        LambdaQueryWrapper<AccountAuthConfig> awrapper = new LambdaQueryWrapper<>();
        awrapper.eq(AccountAuthConfig::getAccountId, account.getId()).eq(AccountAuthConfig::getIsDeleted, Boolean.FALSE);
        AccountAuthConfig config = accountAuthConfigMapper.selectOne(awrapper);
        if (Preconditions.isBlank(config) || Preconditions.isBlank(config.getHhFaceSwitch()) || !config.getHhFaceSwitch() || Preconditions.isBlank(config.getPurchaserId())) {
            throw new BusinessException("禁止访问该资源");
        }
//        List<Long> userLibIds = commonImpl.getAuthModuleIds(account, AuthModuleTypeEnum.HHFACE_USER_LIB);
//        List<Long> tenantIds = commonImpl.getAuthModuleIds(account, AuthModuleTypeEnum.HHFACE_TENANT);
//        if (Preconditions.isBlank(tenantIds) && Preconditions.isBlank(tenantIds)) {
////            throw new BusinessException("未找到访问资源");
//            return RestResult.ok(initEmptyPage());
//        }
//        if (Preconditions.isNotBlank(dto.getTenantId()) && !tenantIds.contains(dto.getTenantId())) {
//            throw new BusinessException("禁止访问该资源");
//        }

        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        //查询的传参条件
        wrapper.like(Preconditions.isNotBlank(dto.getSn()), Device::getSn, dto.getSn());
        wrapper.eq(Preconditions.isNotBlank(dto.getTenantId()), Device::getTenantId, dto.getTenantId());
        wrapper.eq(Preconditions.isNotBlank(dto.getUserLibId()), Device::getUserLibId, dto.getUserLibId());
        wrapper.eq(Device::getPurchaserId, config.getPurchaserId());
        //基础条件
        wrapper.eq(Device::getIsDeleted, Boolean.FALSE);
        wrapper.orderByDesc(Device::getId);
        Page<Device> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        IPage<Device> iPage = deviceMapper.selectPage(page, wrapper);

        Map<Long, Purchaser> purchaserMap = commonImpl.getPurchaserMap(iPage, Device::getPurchaserId);
        Map<Long, ApplicationType> applicationTypeMap = commonImpl.getApplicationTypeMap(iPage, Device::getApplicationTypeId);
        Map<Long, DeviceModel> deviceModelHardwareMap = commonImpl.getDeviceModelMap(iPage, Device::getDeviceModelHardwareId);
        Map<Long, DeviceModel> deviceModelEnvironmentMap = commonImpl.getDeviceModelMap(iPage, Device::getDeviceModelEnvironmentId);

        IPage<DeviceVo> convert = iPage.convert(t -> {
            DeviceVo item = BeanUtil.copyProperties(t, DeviceVo.class);
            item.setZoloConfig(t.getZoloConfig());
            item.setTenantId(t.getTenantId());
            item.setManualInIdCardAuth(t.getManualInIdCard() ? t.getManualInIdCardAuth() : null);
            if (purchaserMap.containsKey(t.getPurchaserId())) {
                item.setCompanyName(purchaserMap.get(t.getPurchaserId()).getCompanyName());
            }
            if (applicationTypeMap.containsKey(t.getApplicationTypeId())) {
                item.setApplicationType(applicationTypeMap.get(t.getApplicationTypeId()).getApplicationType());
            }
            if (deviceModelHardwareMap.containsKey(t.getDeviceModelHardwareId())) {
                item.setDeviceModelHardware(deviceModelHardwareMap.get(t.getDeviceModelHardwareId()).getDeviceModel());
            }
            if (deviceModelEnvironmentMap.containsKey(t.getDeviceModelEnvironmentId())) {
                item.setDeviceModelEnvironment(deviceModelEnvironmentMap.get(t.getDeviceModelEnvironmentId()).getDeviceModel());
            }
            SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(t.getSystemTypeCode());
            if (ObjectUtil.isNotNull(systemTypeEnum)) {
                item.setSystemType(systemTypeEnum.getDesc());
            }
            return item;
        });
        complete(convert);
        return RestResult.ok(convert);
    }

    @Override
    public RestResult<Boolean> update(HhFaceDeviceDto dto, Account account) {
        if (Preconditions.isBlank(dto.getId())) {
            throw new BusinessException("参数有误");
        }
        LambdaQueryWrapper<AccountAuthConfig> awrapper = new LambdaQueryWrapper<>();
        awrapper.eq(AccountAuthConfig::getAccountId, account.getId()).eq(AccountAuthConfig::getIsDeleted, Boolean.FALSE);
        AccountAuthConfig authConfig = accountAuthConfigMapper.selectOne(awrapper);
        if (Preconditions.isBlank(authConfig)
                || Preconditions.isBlank(authConfig.getHhFaceSwitch())
                || !authConfig.getHhFaceSwitch()) {
            throw new BusinessException("禁止修改该资源");
        }

        Device device = deviceMapper.selectById(dto.getId());
        if (device == null || device.getIsDeleted() == null || device.getIsDeleted()) {
            return RestResult.error("数据不存在或已删除");
        }
        BeanUtil.copyProperties(dto, device, "id");
        deviceMapper.updateById(device);
        return RestResult.ok(Boolean.TRUE);
    }

    @Override
    public RestResult<Boolean> addDevice(DeviceDto dto) {

        if (dto.getSn() == null) {
            return RestResult.error("参数有误");
        }

        if (checkSn(dto)) { //校验设备是否存在
            if (dto.getId() != null) {
                return RestResult.error("数据不存在或已删除");
            }
            return RestResult.error("设备已存在");
        }

        Device device = null;

        if (dto.getId() != null) {
            device = deviceMapper.selectById(dto.getId());
            if (device == null || device.getIsDeleted() == null || device.getIsDeleted()) {
                return RestResult.error("数据不存在或已删除");
            }
            dto.setStatus(device.getStatus());
        } else {
            device = new Device();
            device.setStatus(Boolean.TRUE);
            device.setCreateTime(new Date());
            device.setVersion(1);
            device.setIsDeleted(Boolean.FALSE);
            device.setFirstAuthTime(new Date());
        }

        //处理参数
        handleParams(device, dto);

        if (dto.getId() != null) {
            deviceMapper.updateById(device);
        } else {
            deviceMapper.insert(device);
        }
        return RestResult.ok(Boolean.TRUE);
    }

    private void handleParams(Device device, DeviceDto dto) {
        BeanUtil.copyProperties(dto, device);
        //购买方
        if (Preconditions.isNotBlank(dto.getPurchaserId())) {
            Purchaser purchaser = purchaserMapper.selectById(dto.getPurchaserId());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(purchaser), "购买方不存在");
            ClassUtil.throwBusinessException(ObjectUtil.isNull(purchaser.getIsDeleted()), "购买方已删除");
            device.setPurchaserId(purchaser.getId());
        }
        //应用类型
        if (Preconditions.isNotBlank(dto.getApplicationTypeId())) {
            ApplicationType applicationType = applicationTypeMapper.selectById(dto.getApplicationTypeId());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(applicationType), "应用类型不存在");
            ClassUtil.throwBusinessException(ObjectUtil.isNull(applicationType.getIsDeleted()), "购买方已删除");
            device.setApplicationTypeId(applicationType.getId());
        }
        //设备类型（硬件）
        if (Preconditions.isNotBlank(dto.getDeviceModelHardwareId())) {
            DeviceModel deviceModelHardware = deviceModelMapper.selectById(dto.getDeviceModelHardwareId());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelHardware), "设备类型（硬件）不存在");
            ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelHardware.getIsDeleted()), "设备类型（硬件）已删除");
            device.setDeviceModelHardwareId(deviceModelHardware.getId());
        }
        //设备类型（环境）
        if (Preconditions.isNotBlank(dto.getDeviceModelEnvironmentId())) {
            DeviceModel deviceModelEnvironment = deviceModelMapper.selectById(dto.getDeviceModelEnvironmentId());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelEnvironment), "设备类型（环境）不存在");
            ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelEnvironment.getIsDeleted()), "设备类型（环境）已删除");
            device.setDeviceModelEnvironmentId(deviceModelEnvironment.getId());
        }
        //系统类型
        if (Preconditions.isNotBlank(dto.getSystemTypeCode())) {
            SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(dto.getSystemTypeCode());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(systemTypeEnum), "系统类型不存在");
            device.setSystemTypeCode(systemTypeEnum.getCode());
        }
        //进场刷脸模式
        if (Preconditions.isNotBlank(dto.getEntryFaceMode())) {
            EntryFaceModeEnum entryFaceModeEnum = EntryFaceModeEnum.getEnumByCode(dto.getEntryFaceMode());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(entryFaceModeEnum), "进场刷脸模式不存在");
            device.setEntryFaceMode(entryFaceModeEnum.getCode());
        }

        //用户信息输出模式
        if (Preconditions.isNotBlank(dto.getUserOutputMode())) {
            UserOutputModeEnum userOutputModeEnum = UserOutputModeEnum.getEnumByCode(dto.getUserOutputMode());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(userOutputModeEnum), "用户信息输出模式不存在");
            device.setUserOutputMode(userOutputModeEnum.getCode());
        }
        //请选择摄像头类型
        if (ObjectUtil.isNotNull(dto.getCameraType())) {
            CameraTypeEnum cameraTypeEnum = CameraTypeEnum.getEnumByCode(dto.getCameraType());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(cameraTypeEnum), "摄像头类型不存在");
        }
        //摄像头品牌
        if (ObjectUtil.isNotNull(dto.getCameraBrand())) {
            CameraBrandEnum cameraBrandEnum = CameraBrandEnum.getEnumByCode(dto.getCameraBrand());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(cameraBrandEnum), "摄像品牌不存在");
        }
        //继电器开门模式
        if (ObjectUtil.isNotNull(dto.getRelayOpenModel())) {
            RelayOpenModelEnum relayOpenModelEnum = RelayOpenModelEnum.getEnumByCode(dto.getRelayOpenModel());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(relayOpenModelEnum), "继电器开门模式不存在");
        }
        //Ic14443阅读器品牌
        if (ObjectUtil.isNotNull(dto.getIc14443ReaderBrand())) {
            ReaderBrandEnum readerBrandEnum = ReaderBrandEnum.queryEnumByCode(dto.getIc14443ReaderBrand());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(readerBrandEnum), "Ic14443阅读器品牌不存在");
        }
        //Ic15693阅读器品牌
        if (ObjectUtil.isNotNull(dto.getIc15693ReaderBrand())) {
            ReaderBrandEnum readerBrandEnum = ReaderBrandEnum.queryEnumByCode(dto.getIc14443ReaderBrand());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(readerBrandEnum), "Ic15693阅读器品牌不存在");
        }

        device.setMode(dto.getMode());
        device.setSn(dto.getSn());
        device.setTenantId(dto.getTenantId());
        device.setSceneId(dto.getSceneId());
        device.setUserLibId(dto.getUserLibId());
        device.setCompany(dto.getCompany());
        device.setUpdateTime(new Date());
        //TODO 20230921添加参数
        device.setUseAlipayFace(dto.getUseAlipayFace() != null ? dto.getUseAlipayFace() : DeviceDefaultParam.defaultUseAlipayFace);
        device.setLinkageAds(dto.getLinkageAds() != null ? dto.getLinkageAds() : DeviceDefaultParam.defaultLinkageAds);
        device.setSuccessPageTime(dto.getSuccessPageTime() != null ? dto.getSuccessPageTime() : DeviceDefaultParam.defaultSuccessPageTime);
        device.setFailPageTime(dto.getFailPageTime() != null ? dto.getFailPageTime() : DeviceDefaultParam.defaultFailPageTime);
        device.setZoloConfig(dto.getZoloConfig() != null ? dto.getZoloConfig() : DeviceDefaultParam.initZoloConfig());
        device.setUseIdcard(dto.getUseIdcard() != null ? dto.getUseIdcard() : DeviceDefaultParam.defaultUseIdcard);
        device.setUsePersonCard(dto.getUsePersonCard() != null ? dto.getUsePersonCard() : DeviceDefaultParam.defaultUsePersonCard);
        device.setUseQrcode(dto.getUseQrcode() != null ? dto.getUseQrcode() : DeviceDefaultParam.defaultUseQrcode);
        device.setUseLinkage(dto.getUseLinkage() != null ? dto.getUseLinkage() : DeviceDefaultParam.defaultUseLinkage);
        device.setFaceMode(dto.getFaceMode() != null ? dto.getFaceMode() : DeviceDefaultParam.defaultFaceMode);
        device.setClickButtonText(dto.getClickButtonText() != null ? dto.getClickButtonText() : DeviceDefaultParam.defaultClickButtonText);
        device.setIsCaptureFace(dto.getIsCaptureFace() != null ? dto.getIsCaptureFace() : DeviceDefaultParam.defaultIsCaptureFace);
        device.setIsNeed1V1(dto.getIsNeed1V1() != null ? dto.getIsNeed1V1() : DeviceDefaultParam.defaultIsNeed1V1);
        device.setUseSerialPort(dto.getUseSerialPort() != null ? dto.getUseSerialPort() : DeviceDefaultParam.defaultUseSerialPort);
        device.setSignalNo(dto.getSignalNo());
        device.setLightMode(dto.getLightMode() != null ? dto.getLightMode() : DeviceDefaultParam.defaultLightMode);
        device.setVolume(dto.getVolume() != null ? dto.getVolume() : DeviceDefaultParam.defaultVolume);
        device.setSucVoice(dto.getSucVoice() != null ? dto.getSucVoice() : DeviceDefaultParam.defaultSucVoice);
        device.setSucText(dto.getSucText() != null ? dto.getSucText() : DeviceDefaultParam.defaultSucText);
        device.setFailVoice(dto.getFailVoice() != null ? dto.getFailVoice() : DeviceDefaultParam.defaultFailVoice);
        device.setFailText(dto.getFailText() != null ? dto.getFailText() : DeviceDefaultParam.defaultFailText);
        device.setHideNavigationBar(dto.getHideNavigationBar() != null ? dto.getHideNavigationBar() : DeviceDefaultParam.defaultHideNavigationBar);
        device.setForbidPullDown(dto.getForbidPullDown() != null ? dto.getForbidPullDown() : DeviceDefaultParam.defaultForbidPullDown);
        device.setHomePageUrl(dto.getHomePageUrl() != null ? dto.getHomePageUrl() : DeviceDefaultParam.defaultHomePageUrl);
        device.setTransitionPageUrl(dto.getTransitionPageUrl() != null ? dto.getTransitionPageUrl() : DeviceDefaultParam.defaultTransitionPageUrl);
        //TODO 20231007添加参数
        device.setHeartTrackingUrl(dto.getHeartTrackingUrl() != null ? dto.getHeartTrackingUrl() : DeviceDefaultParam.defaultHeartTrackingUrl);
        device.setTransitPushUrl(dto.getTransitPushUrl() != null ? dto.getTransitPushUrl() : DeviceDefaultParam.defaultTransitPushUrl);
        device.setShowTopBar(dto.getShowTopBar() != null ? dto.getShowTopBar() : DeviceDefaultParam.defaultShowTopBar);
        device.setLeftTopBarText(dto.getLeftTopBarText() != null ? dto.getLeftTopBarText() : DeviceDefaultParam.defaultLeftTopBarText);
        device.setRightTopBarText(dto.getRightTopBarText() != null ? dto.getRightTopBarText() : DeviceDefaultParam.defaultRightTopBarText);
        device.setPassWay(dto.getPassWay() != null ? dto.getPassWay() : DeviceDefaultParam.defaultPassWay);
        //TODO 20231110添加参数
        device.setIsOpenAgeLimit(dto.getIsOpenAgeLimit() != null ? dto.getIsOpenAgeLimit() : DeviceDefaultParam.defaultIsOpenAgeLimit);
        device.setLimitSectionStart(dto.getLimitSectionStart());
        device.setLimitSectionEnd(dto.getLimitSectionEnd());
        device.setAgeForbidText(dto.getAgeForbidText() != null ? dto.getAgeForbidText() : DeviceDefaultParam.defaultAgeForbidText);
        device.setMpassword(dto.getMpassword() != null ? dto.getMpassword() : DeviceDefaultParam.defaultMpassword);
        //TODO 20231128添加参数
        device.setIsOpenPassport(dto.getIsOpenPassport() != null ? dto.getIsOpenPassport() : DeviceDefaultParam.isOpenPassport);
        device.setIsPushGM(dto.getIsPushGM() != null ? dto.getIsPushGM() : DeviceDefaultParam.isPushGM);
        device.setGMAddress(dto.getGMAddress() != null ? dto.getGMAddress() : DeviceDefaultParam.GMAddress);
        device.setGMFrequency(dto.getGMFrequency() != null ? dto.getGMFrequency() : DeviceDefaultParam.GMFrequency);
        device.setAutoLaunch(dto.getAutoLaunch() != null ? dto.getAutoLaunch() : DeviceDefaultParam.autoLaunch);
        //TODO 20231215添加参数
        device.setUseEntryDetector(dto.getUseEntryDetector() != null ? dto.getUseEntryDetector() : DeviceDefaultParam.useEntryDetector);
        //TODO 20240103添加参数
        device.setLogPushUrl(dto.getLogPushUrl() != null ? dto.getLogPushUrl() : DeviceDefaultParam.defaultLogPushUrl);
        device.setCameraType(dto.getCameraType() != null ? dto.getCameraType() : DeviceDefaultParam.cameraType);
        device.setCameraBrand(dto.getCameraBrand() != null ? dto.getCameraBrand() : DeviceDefaultParam.cameraBrand);
        //TODO 20240105添加参数
        device.setEntryFaceMode(StrUtil.isNotBlank(device.getEntryFaceMode()) ? device.getEntryFaceMode() : DeviceDefaultParam.entryFaceMode);
        //TODO 20240228添加参数
        device.setUserOutputMode(dto.getUserOutputMode() != null ? dto.getUserOutputMode() : DeviceDefaultParam.defaultUserOutputMode);
        device.setIdCardReaderBrand(dto.getIdCardReaderBrand() != null ? dto.getIdCardReaderBrand() : DeviceDefaultParam.defaultIdCardReaderBrand);
        //TODO 20240315添加参数
        device.setAuthVerifiedFacein(dto.getAuthVerifiedFacein() != null ? dto.getAuthVerifiedFacein() : Boolean.FALSE);
        device.setManualInIdCard(dto.getManualInIdCard() != null ? dto.getManualInIdCard() : Boolean.FALSE);
        device.setManualInIdCardAuth(dto.getManualInIdCardAuth());
        //TODO 20240327添加参数
//        device.setLinkageCheckMode((!dto.getUseLinkage() || LinkageCheckModeEnum.getEnumByCode(dto.getLinkageCheckMode()) == null) ? DeviceDefaultParam.defaultLinkageCheckMode : dto.getLinkageCheckMode());
        device.setResultPageTemplate(ResultPageTemplateEnum.getEnumByCode(dto.getResultPageTemplate()) != null ? dto.getResultPageTemplate() : DeviceDefaultParam.defaultResultPageTemplate);
        //TODO 20240423添加参数
        device.setRelayOpenModel(dto.getRelayOpenModel());
        if (RelayOpenModelEnum.OPEN_CLOSE.getCode().equals(dto.getRelayOpenModel())) {
            device.setOpenCloseInterval(dto.getOpenCloseInterval() == null ? DeviceDefaultParam.defaultOpenCloseInterval : dto.getOpenCloseInterval());
            device.setSignalInterval(dto.getSignalInterval() == null ? DeviceDefaultParam.defaultSignalInterval : dto.getSignalInterval());
        } else if (RelayOpenModelEnum.OPEN_GATE_CLOSE.getCode().equals(dto.getRelayOpenModel())) {
            device.setGateTimeOut(dto.getGateTimeOut() == null ? DeviceDefaultParam.defaultGateTimeOut : dto.getGateTimeOut());
        }
        //TODO 20240503添加参数
        device.setAnalysisPhoto(dto.getAnalysisPhoto() == null ? DeviceDefaultParam.defaultAnalysisPhoto : dto.getAnalysisPhoto());
        device.setAnalysisFingerprint(dto.getAnalysisFingerprint() == null ? DeviceDefaultParam.defaultAnalysisFingerprint : dto.getAnalysisFingerprint());
        //TODO 20240506添加参数
        device.setIdCardInterval(dto.getIdCardInterval() == null ? DeviceDefaultParam.defaultIdCardInterval : dto.getIdCardInterval());
        //TODO 20240520添加参数
        device.setCommunicationMode(dto.getCommunicationMode());
        device.setWsAddress(dto.getWsAddress());
        device.setCommunicationSerialPort(dto.getCommunicationSerialPort());
        device.setDoorSerialPort(dto.getDoorSerialPort());
        //联动平台超时时间
        device.setLinkTimeout(dto.getLinkTimeout());
        device.setOpenDelayTime(dto.getOpenDelayTime());
        //todo 20240604
        device.setAnonymousStorage(dto.getAnonymousStorage() == null ? DeviceDefaultParam.defaultAnonymousStorage : dto.getAnonymousStorage());
        device.setCompareSilentDisplay(dto.getCompareSilentDisplay() == null ? DeviceDefaultParam.defaultCompareSilentDisplay : dto.getCompareSilentDisplay());
        device.setCompareSilentDisplayTime(dto.getCompareSilentDisplayTime() == null ? DeviceDefaultParam.defaultCompareSilentDisplayTime : dto.getCompareSilentDisplayTime());
        device.setCompareTopTitle(dto.getCompareTopTitle());
        //todo 20240807
        device.setLedBrightness(dto.getLedBrightness());
        //todo 20240819
        device.setVerifyRetryTimes(dto.getVerifyRetryTimes());
        device.setVerifyLinkTimeout(dto.getVerifyLinkTimeout());
        device.setScheduledRestart(dto.getScheduledRestart());
        device.setScheduledRestartTime(dto.getScheduledRestartTime());
        //todo 20240822
        device.setIc14443IcCardFunction(dto.getIc14443IcCardFunction());
        device.setIc14443ReaderBrand(dto.getIc14443ReaderBrand());
        device.setIc14443ReaderSectorNumbers(dto.getIc14443ReaderSectorNumbers());
        device.setIc14443ReaderBlock(dto.getIc14443ReaderBlock());
        device.setIc14443ReaderKey(dto.getIc14443ReaderKey());
        device.setIc14443StartOffset(dto.getIc14443StartOffset());
        device.setIc14443EndOffset(dto.getIc14443EndOffset());
        device.setIc14443PersonCardComparison(dto.getIc14443PersonCardComparison());
        device.setIc14443SameCardIntervalTime(dto.getIc14443SameCardIntervalTime());
        device.setIc15693IcCardFunction(dto.getIc15693IcCardFunction());
        device.setIc15693ReaderBrand(dto.getIc15693ReaderBrand());
        device.setIc15693ReaderBlock(dto.getIc15693ReaderBlock());
        device.setIc15693StartOffset(dto.getIc15693StartOffset());
        device.setIc15693EndOffset(dto.getIc15693EndOffset());
        device.setIc15693PersonCardComparison(dto.getIc15693PersonCardComparison());
        device.setIc15693SameCardIntervalTime(dto.getIc15693SameCardIntervalTime());
        //todo 20240822
        device.setExpirationDate(dto.getExpirationDate());

    }

    private Boolean checkSn(DeviceDto dto) {
        List<Device> devices = deviceMapper.selectList(Wrappers.lambdaQuery(Device.class).eq(Device::getSn, dto.getSn()).eq(Device::getIsDeleted, Boolean.FALSE));
        if (devices != null && devices.size() > 0) {
            if (dto.getId() == null) {
                return Boolean.TRUE;
            } else {
                List<Long> ids = devices.stream().map(Device::getId).collect(Collectors.toList());
                if (!ids.contains(dto.getId())) {
                    return Boolean.TRUE;
                }
            }
        }
        return Boolean.FALSE;
    }

    @Override
    public RestResult<Boolean> opeDeviceAuth(Long deviceId, Boolean auth) {
        Device device = deviceMapper.selectById(deviceId);
        if (device != null && !device.getIsDeleted()) {
            device.setStatus(auth);
            device.setUpdateTime(new Date());
            deviceMapper.updateById(device);
        }
        return RestResult.ok(Boolean.TRUE);
    }

    @Override
    public RestResult<Boolean> deviceDel(Long deviceId) {
        Device device = deviceMapper.selectById(deviceId);
        if (device != null && device.getIsDeleted() != null && !device.getIsDeleted()) {
            deviceMapper.deleteById(device);
        }
        return RestResult.ok(Boolean.TRUE);
    }

    @Override
    public TenantVo getThirdAppAuthTokenBySn(String sn) {
        if (sn == null || "".equals(sn.trim())) {
            return null;
        }
        List<Device> devices = deviceMapper.selectList(Wrappers.lambdaQuery(Device.class).eq(Device::getStatus, Boolean.TRUE).isNotNull(Device::getTenantId).eq(Device::getSn, sn).eq(Device::getIsDeleted, Boolean.FALSE));
        if (devices == null || devices.size() == 0) {
            return null;
        }
        List<Long> tenantIds = devices.stream().filter(item -> item.getTenantId() != null).map(Device::getTenantId).collect(Collectors.toList());
        LambdaQueryWrapper<Tenant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tenant::getIsDeleted, Boolean.FALSE)
                .isNotNull(Tenant::getServiceAppId)
                .eq(Tenant::getThirdAuth, Boolean.TRUE)
                .isNotNull(Tenant::getAppAuthToken)
                .isNotNull(Tenant::getAppAuthTokenStatus)
                .eq(Tenant::getAppAuthTokenStatus, Boolean.TRUE)
                .in(Tenant::getId, tenantIds);
        List<Tenant> list = tenantMapper.selectList(wrapper);
        List<TenantVo> vos = BeanUtil.copyToList(list, TenantVo.class);
        return (vos != null && vos.size() > 0) ? vos.get(0) : null;
    }

    @Override
    public TenantVo getBySn(String sn) {
        if (sn == null || "".equals(sn.trim())) {
            return null;
        }
        List<Device> devices = deviceMapper.selectList(Wrappers.lambdaQuery(Device.class).eq(Device::getStatus, Boolean.TRUE).isNotNull(Device::getTenantId).eq(Device::getSn, sn).eq(Device::getIsDeleted, Boolean.FALSE));
        if (devices == null || devices.size() == 0) {
            return null;
        }
        List<Long> tenantIds = devices.stream().filter(item -> item.getTenantId() != null).map(Device::getTenantId).collect(Collectors.toList());
        LambdaQueryWrapper<Tenant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tenant::getIsDeleted, Boolean.FALSE).in(Tenant::getId, tenantIds);
        List<Tenant> list = tenantMapper.selectList(wrapper);
        List<TenantVo> vos = BeanUtil.copyToList(list, TenantVo.class);
        return (vos != null && vos.size() > 0) ? vos.get(0) : null;
    }

    @Override
    public void updateAppAccessTokenByAppId(String thirdAuthAppId, String accessToken) {
        LambdaQueryWrapper<Tenant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tenant::getIsDeleted, Boolean.FALSE).eq(Tenant::getServiceAppId, thirdAuthAppId).eq(Tenant::getThirdAuth, Boolean.TRUE);
        List<Tenant> list = tenantMapper.selectList(wrapper);
        if (list == null || list.size() == 0) {
            return;
        }
        list.stream().forEach(item -> {
            item.setAppAuthToken(accessToken);
            item.setAppAuthTokenStatus(Boolean.TRUE);
            item.setThirdAuth(Boolean.TRUE);
            tenantMapper.updateById(item);
        });

    }

    @Override
    public void appAuthCancelled(AlipayAppAuthCancelledMqRequest request) {
        LambdaQueryWrapper<Tenant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tenant::getIsDeleted, Boolean.FALSE).eq(Tenant::getThirdAuth, Boolean.TRUE).eq(Tenant::getServiceAppId, request.getAuthAppId()).eq(Tenant::getAppAuthToken, request.getAppAuthToken());
        List<Tenant> list = tenantMapper.selectList(wrapper);
        list.stream().forEach(item -> {
            item.setThirdAuth(Boolean.FALSE);
            item.setAppAuthTokenStatus(Boolean.FALSE);
            item.setAppAuthToken(null);
            tenantMapper.updateById(item);
        });
    }

    @Override
    public RestResult<Boolean> opeAuth(Long id, Boolean flag) {
        LambdaQueryWrapper<Tenant> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNotNull(Tenant::getServiceAppId).isNotNull(Tenant::getAppAuthToken).eq(Tenant::getIsDeleted, Boolean.FALSE).eq(Tenant::getId, id);
        List<Tenant> list = tenantMapper.selectList(wrapper);
        list.stream().forEach(item -> {
            item.setAppAuthTokenStatus(flag);
            tenantMapper.updateById(item);
        });
        return RestResult.ok(Boolean.TRUE);
    }

    @Override
    public RestResult<Boolean> deviceOpConfig(DeviceOpConfigDto dto) {
        if (dto.getSn() == null) {
            return RestResult.error("参数有误");
        }
        List<Device> devices = deviceMapper.selectList(Wrappers.lambdaQuery(Device.class).eq(Device::getSn, dto.getSn()).eq(Device::getIsDeleted, Boolean.FALSE));
        if (devices == null || devices.size() == 0) {
            return RestResult.error("数据不存在或已删除");
        }

        Device device = devices.get(0);
        device.setUpdateTime(new Date());
        //TODO 20230921添加参数
        if (dto.getUseAlipayFace() != null) {
            device.setUseAlipayFace(dto.getUseAlipayFace());
        }
        if (StrUtil.isNotBlank(dto.getLinkageAds())) {
            device.setLinkageAds(dto.getLinkageAds());
        }
        if (dto.getSuccessPageTime() != null) {
            device.setSuccessPageTime(dto.getSuccessPageTime());
        }
        if (dto.getFailPageTime() != null) {
            device.setFailPageTime(dto.getFailPageTime());
        }
        if (dto.getZoloConfig() != null) {
            device.setZoloConfig(dto.getZoloConfig());
        }
        if (dto.getUseIdcard() != null) {
            device.setUseIdcard(dto.getUseIdcard());
        }
        if (dto.getUsePersonCard() != null) {
            device.setUsePersonCard(dto.getUsePersonCard());
        }
        if (dto.getUseQrcode() != null) {
            device.setUseQrcode(dto.getUseQrcode());
        }
        if (dto.getUseLinkage() != null) {
            device.setUseLinkage(dto.getUseLinkage());
        }
        if (StrUtil.isNotBlank(dto.getFaceMode())) {
            device.setFaceMode(dto.getFaceMode());
        }
        if (StrUtil.isNotBlank(dto.getClickButtonText())) {
            device.setClickButtonText(dto.getClickButtonText());
        }
        if (dto.getIsCaptureFace() != null) {
            device.setIsCaptureFace(dto.getIsCaptureFace());
        }
        if (dto.getIsNeed1V1() != null) {
            device.setIsNeed1V1(dto.getIsNeed1V1());
        }
        if (StrUtil.isNotBlank(dto.getUseSerialPort())) {
            device.setUseSerialPort(dto.getUseSerialPort());
        }
        if (StrUtil.isNotBlank(dto.getSignalNo())) {
            device.setSignalNo(dto.getSignalNo());
        }
        if (StrUtil.isNotBlank(dto.getLightMode())) {
            device.setLightMode(dto.getLightMode());
        }
        if (dto.getVolume() != null) {
            device.setVolume(dto.getVolume());
        }
        if (StrUtil.isNotBlank(dto.getSucVoice())) {
            device.setSucVoice(dto.getSucVoice());
        }
        if (StrUtil.isNotBlank(dto.getSucText())) {
            device.setSucText(dto.getSucText());
        }
        if (StrUtil.isNotBlank(dto.getFailVoice())) {
            device.setFailVoice(dto.getFailVoice());
        }
        if (StrUtil.isNotBlank(dto.getFailText())) {
            device.setFailText(dto.getFailText());
        }
        if (dto.getHideNavigationBar() != null) {
            device.setHideNavigationBar(dto.getHideNavigationBar());
        }
        if (dto.getForbidPullDown() != null) {
            device.setForbidPullDown(dto.getForbidPullDown());
        }
        if (StrUtil.isNotBlank(dto.getHomePageUrl())) {
            device.setHomePageUrl(dto.getHomePageUrl());
        }
        if (StrUtil.isNotBlank(dto.getTransitionPageUrl())) {
            device.setTransitionPageUrl(dto.getTransitionPageUrl());
        }

        //TODO。。。20231007添加
        if (StrUtil.isNotBlank(dto.getHeartTrackingUrl())) {
            device.setHeartTrackingUrl(dto.getHeartTrackingUrl());
        }
        if (StrUtil.isNotBlank(dto.getTransitPushUrl())) {
            device.setTransitPushUrl(dto.getTransitPushUrl());
        }
        if (dto.getShowTopBar() != null) {
            device.setShowTopBar(dto.getShowTopBar());
        }
        if (StrUtil.isNotBlank(dto.getLeftTopBarText())) {
            device.setLeftTopBarText(dto.getLeftTopBarText());
        }
        if (StrUtil.isNotBlank(dto.getRightTopBarText())) {
            device.setRightTopBarText(dto.getRightTopBarText());
        }
        if (StrUtil.isNotBlank(dto.getPassWay())) {
            device.setPassWay(dto.getPassWay());
        }
        //TODO。。。20231110添加
        if (dto.getIsOpenAgeLimit() != null) {
            device.setIsOpenAgeLimit(dto.getIsOpenAgeLimit());
        }
        if (dto.getLimitSectionStart() != null) {
            device.setLimitSectionStart(dto.getLimitSectionStart());
        }
        if (dto.getLimitSectionEnd() != null) {
            device.setLimitSectionEnd(dto.getLimitSectionEnd());
        }
        if (StrUtil.isNotBlank(dto.getAgeForbidText())) {
            device.setAgeForbidText(dto.getAgeForbidText());
        }
        //TODO。。。20231128添加
        if (dto.getIsOpenPassport() != null) {
            device.setIsOpenPassport(dto.getIsOpenPassport());
        }
        if (dto.getIsPushGM() != null) {
            device.setIsPushGM(dto.getIsPushGM());
        }
        if (StrUtil.isNotBlank(dto.getGMAddress())) {
            device.setGMAddress(dto.getGMAddress());
        }
        if (dto.getGMFrequency() != null) {
            device.setGMFrequency(dto.getGMFrequency());
        }
        if (dto.getAutoLaunch() != null) {
            device.setAutoLaunch(dto.getAutoLaunch());
        }
        //TODO。。。20231215添加
        if (dto.getUseEntryDetector() != null) {
            device.setUseEntryDetector(dto.getUseEntryDetector());
        }
        //TODO。。。20240103添加
        if (StrUtil.isNotBlank(dto.getLogPushUrl())) {
            device.setLogPushUrl(dto.getLogPushUrl());
        }
        //摄像头类型
        if (ObjectUtil.isNotNull(dto.getCameraType())) {
            CameraTypeEnum cameraTypeEnum = CameraTypeEnum.getEnumByCode(dto.getCameraType());
            if (ObjectUtil.isNotNull(cameraTypeEnum)) {
                device.setCameraType(dto.getCameraType());
            }
        }
        //摄像头品牌
        if (ObjectUtil.isNotNull(dto.getCameraBrand())) {
            CameraBrandEnum cameraBrandEnum = CameraBrandEnum.getEnumByCode(dto.getCameraBrand());
            if (ObjectUtil.isNotNull(cameraBrandEnum)) {
                device.setCameraBrand(dto.getCameraBrand());
            }
        }
        //TODO。。。20240105添加
        //进场刷脸模式
        if (ObjectUtil.isNotNull(dto.getEntryFaceMode())) {
            EntryFaceModeEnum entryFaceModeEnum = EntryFaceModeEnum.getEnumByCode(dto.getEntryFaceMode());
            if (ObjectUtil.isNotNull(entryFaceModeEnum)) {
                device.setEntryFaceMode(dto.getEntryFaceMode());
            }
        }
        //TODO。。。20240228添加
        if (ObjectUtil.isNotNull(dto.getUserOutputMode())) {
            UserOutputModeEnum userOutputModeEnum = UserOutputModeEnum.getEnumByCode(dto.getUserOutputMode());
            if (ObjectUtil.isNotNull(userOutputModeEnum)) {
                device.setUserOutputMode(dto.getUserOutputMode());
            }
        }
        //TODO。。。20240315添加
        if (Preconditions.isNotBlank(dto.getAuthVerifiedFacein())) {
            device.setAuthVerifiedFacein(dto.getAuthVerifiedFacein());
        }
        if (Preconditions.isNotBlank(dto.getManualInIdCard())) {
            device.setManualInIdCard(dto.getManualInIdCard());
        }
        //TODO。。。20240313添加
        if (ObjectUtil.isNotNull(dto.getIdCardReaderBrand())) {
            IdCardReaderBrandEnum idCardReaderBrandEnum = IdCardReaderBrandEnum.queryEnumByCode(dto.getIdCardReaderBrand());
            if (ObjectUtil.isNotNull(idCardReaderBrandEnum)) {
                device.setIdCardReaderBrand(dto.getIdCardReaderBrand());
            }
        }
        //TODO。。。20240503添加
        if (Preconditions.isNotBlank(dto.getAnalysisPhoto())) {
            device.setAnalysisPhoto(dto.getAnalysisPhoto());
        }
        if (Preconditions.isNotBlank(dto.getAnalysisFingerprint())) {
            device.setAnalysisFingerprint(dto.getAnalysisFingerprint());
        }
        //TODO。。。20240506添加
        if (Preconditions.isNotBlank(dto.getIdCardInterval())) {
            if (dto.getIdCardInterval() >= 0 && dto.getIdCardInterval() <= 20) {
                device.setIdCardInterval(dto.getIdCardInterval());
            }
        }
        if (Preconditions.isNotBlank(dto.getDoorSerialPort())) {
            device.setDoorSerialPort(dto.getDoorSerialPort());
        }
        if (Preconditions.isNotBlank(dto.getScheduledRestart())) {
            device.setScheduledRestart(dto.getScheduledRestart());
        }
        if (Preconditions.isNotBlank(dto.getScheduledRestartTime())) {
            device.setScheduledRestartTime(dto.getScheduledRestartTime());
        }
        if (Preconditions.isNotBlank(dto.getOpenCloseInterval())) {
            device.setOpenCloseInterval(dto.getOpenCloseInterval());
        }
        if (Preconditions.isNotBlank(dto.getSignalInterval())) {
            device.setSignalInterval(dto.getSignalInterval());
        }
        if (Preconditions.isNotBlank(dto.getRelayOpenModel())) {
            device.setRelayOpenModel(dto.getRelayOpenModel());
        }

        device.setMpassword(dto.getMpassword());
        deviceMapper.updateById(device);
        return RestResult.ok(Boolean.TRUE);
    }

    @Override
    public RestResult<List<String>> snlist() {
        List<Device> devices = deviceMapper.selectList(Wrappers.lambdaQuery(Device.class).select(Device::getSn).eq(Device::getStatus, Boolean.TRUE).eq(Device::getIsDeleted, Boolean.FALSE));
        List<String> sns = devices.stream().map(Device::getSn).collect(Collectors.toList());
        return RestResult.ok(sns == null || sns.isEmpty() ? Collections.emptyList() : sns);
    }

    @Override
    public RestResult<Boolean> add(TenantReqDto dto) {
        Tenant tenant = null;
        if (dto.getId() != null) {
            tenant = tenantMapper.selectById(dto.getId());
            if (tenant == null || tenant.getIsDeleted() == null || tenant.getIsDeleted()) {
                return RestResult.error("数据不存在或已删除");
            }
            tenant.setMachineAppId(dto.getMachineAppId());
            tenant.setName(dto.getName());
            tenant.setServiceAddress(dto.getServiceAddress());
            tenant.setServiceAppId(dto.getServiceAppId());
            tenant.setThirdAuth(dto.getThirdAuth() == null ? Boolean.FALSE : dto.getThirdAuth());
            tenant.setAppAuthToken(dto.getAppAuthToken());
            tenant.setAppAuthTokenStatus(Boolean.TRUE);
            tenant.setUpdateTime(new Date());
            tenant.setFaceinAddress(dto.getFaceinAddress());
            tenantMapper.updateById(tenant);
        } else {
            tenant = BeanUtil.copyProperties(dto, Tenant.class);
            tenant.setCreateTime(new Date());
            tenant.setUpdateTime(new Date());
            tenant.setVersion(1);
            tenant.setIsDeleted(Boolean.FALSE);
            tenant.setAppAuthToken(dto.getAppAuthToken());
            tenant.setAppAuthTokenStatus(Boolean.TRUE);
            tenant.setThirdAuth(dto.getThirdAuth() == null ? Boolean.FALSE : dto.getThirdAuth());
            tenantMapper.insert(tenant);
        }

        return RestResult.ok(Boolean.TRUE);
    }

    @Override
    public RestResult<Boolean> del(Long id) {
        Tenant tenant = tenantMapper.selectById(id);
        if (tenant != null) {
            //
            List<Device> devices = deviceMapper.selectList(Wrappers.lambdaQuery(Device.class).eq(Device::getTenantId, id).eq(Device::getIsDeleted, Boolean.FALSE));
            if (devices != null && devices.size() > 0) {
                List<String> sns = devices.stream().map(Device::getSn).collect(Collectors.toList());
                String join = StringUtils.join(sns, ",");
                return RestResult.error(String.format("商户平台下有设备绑定【%s】无法删除", join));
            }
            tenant.setUpdateTime(new Date());
            tenant.setIsDeleted(Boolean.TRUE);
            tenantMapper.updateById(tenant);
        }

        return RestResult.ok(Boolean.TRUE);
    }

    @Override
    public RestResult<IPage<TenantVo>> page(TenantReqDto dto) {
        Page<Tenant> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        LambdaQueryWrapper<Tenant> wrapper = getTenantLambdaQueryWrapper(dto);
        IPage<Tenant> iPage = tenantMapper.selectPage(page, wrapper);
        IPage<TenantVo> convert = iPage.convert(t -> {
            TenantVo item = BeanUtil.copyProperties(t, TenantVo.class);
            return item;
        });
        return RestResult.ok(convert);
    }

    @NotNull
    private static LambdaQueryWrapper<Tenant> getTenantLambdaQueryWrapper(TenantReqDto dto) {
        LambdaQueryWrapper<Tenant> wrapper = new LambdaQueryWrapper<>();
        if (dto.getName() != null && !"".equals(dto.getName().trim())) {
            wrapper.like(Tenant::getName, dto.getName().trim());
        }
        wrapper.like(ObjectUtil.isNotNull(dto.getMachineAppId()), Tenant::getMachineAppId, dto.getMachineAppId());
        wrapper.like(ObjectUtil.isNotNull(dto.getServiceAppId()), Tenant::getServiceAppId, dto.getServiceAppId());
        wrapper.eq(Tenant::getIsDeleted, Boolean.FALSE).orderByDesc(Tenant::getId);
        return wrapper;
    }

    @Override
    public RestResult<Boolean> opDevice(DeviceDto dto) {
//        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(Device::getSn, dto.getSn()).eq(Device::getIsDeleted, Boolean.FALSE);
//        Device device = deviceMapper.selectOne(wrapper);
//        if (StringUtils.equals("00", dto.getType())) {//授权
//            if (device == null) {
//                device = new Device();
//                device.setSn(dto.getSn());
////                device.setTenantId(dto.getTenantId());
//                device.setIsDeleted(Boolean.FALSE);
//                device.setFirstAuthTime(new Date());
//                device.setCreateTime(new Date());
//                device.setStatus(Boolean.TRUE);
//                device.setUpdateTime(new Date());
//                deviceMapper.insert(device);
//            } else {
////                device.setTenantId(dto.getTenantId());
//                device.setStatus(Boolean.TRUE);
//                device.setUpdateTime(new Date());
//                deviceMapper.updateById(device);
//            }
//        } else if (StringUtils.equals("01", dto.getType()) && device != null) {//停用
//            device.setStatus(Boolean.FALSE);
//            device.setUpdateTime(new Date());
////            device.setTenantId(null);
//            deviceMapper.updateById(device);
//        }
        return RestResult.ok(Boolean.TRUE);
    }

    @Override
    public RestResult<IPage<DeviceVo>> snPage(DeviceDto dto) {
        LambdaQueryWrapper<Device> wrapper = this.getWrapper(dto);
        Page<Device> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        IPage<Device> iPage = deviceMapper.selectPage(page, wrapper);

        Map<Long, Purchaser> purchaserMap = commonImpl.getPurchaserMap(iPage, Device::getPurchaserId);
        Map<Long, ApplicationType> applicationTypeMap = commonImpl.getApplicationTypeMap(iPage, Device::getApplicationTypeId);
        Map<Long, DeviceModel> deviceModelHardwareMap = commonImpl.getDeviceModelMap(iPage, Device::getDeviceModelHardwareId);
        Map<Long, DeviceModel> deviceModelEnvironmentMap = commonImpl.getDeviceModelMap(iPage, Device::getDeviceModelEnvironmentId);

        IPage<DeviceVo> convert = iPage.convert(t -> {
            DeviceVo item = BeanUtil.copyProperties(t, DeviceVo.class);
            item.setZoloConfig(t.getZoloConfig());
            item.setTenantId(t.getTenantId());
            item.setManualInIdCardAuth(t.getManualInIdCard() ? t.getManualInIdCardAuth() : null);
            if (purchaserMap.containsKey(t.getPurchaserId())) {
                item.setCompanyName(purchaserMap.get(t.getPurchaserId()).getCompanyName());
            }
            if (applicationTypeMap.containsKey(t.getApplicationTypeId())) {
                item.setApplicationType(applicationTypeMap.get(t.getApplicationTypeId()).getApplicationType());
            }
            if (deviceModelHardwareMap.containsKey(t.getDeviceModelHardwareId())) {
                item.setDeviceModelHardware(deviceModelHardwareMap.get(t.getDeviceModelHardwareId()).getDeviceModel());
            }
            if (deviceModelEnvironmentMap.containsKey(t.getDeviceModelEnvironmentId())) {
                item.setDeviceModelEnvironment(deviceModelEnvironmentMap.get(t.getDeviceModelEnvironmentId()).getDeviceModel());
            }
            SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(t.getSystemTypeCode());
            if (ObjectUtil.isNotNull(systemTypeEnum)) {
                item.setSystemType(systemTypeEnum.getDesc());
            }
            return item;
        });
        complete(convert);
        return RestResult.ok(convert);
    }

    private LambdaQueryWrapper<Device> getWrapper(DeviceDto dto) {
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        //查询的传参条件
        wrapper.like(StrUtil.isNotBlank(dto.getSn()), Device::getSn, dto.getSn());
        wrapper.eq(ObjectUtil.isNotNull(dto.getPurchaserId()), Device::getPurchaserId, dto.getPurchaserId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getApplicationTypeId()), Device::getApplicationTypeId, dto.getApplicationTypeId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getDeviceModelHardwareId()), Device::getDeviceModelHardwareId, dto.getDeviceModelHardwareId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getDeviceModelEnvironmentId()), Device::getDeviceModelEnvironmentId, dto.getDeviceModelEnvironmentId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getSystemTypeCode()), Device::getSystemTypeCode, dto.getSystemTypeCode());
        wrapper.eq(ObjectUtil.isNotNull(dto.getTenantId()), Device::getTenantId, dto.getTenantId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getUserLibId()), Device::getUserLibId, dto.getUserLibId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getSceneId()), Device::getSceneId, dto.getSceneId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getMode()), Device::getMode, dto.getMode());
        wrapper.eq(ObjectUtil.isNotNull(dto.getStatus()), Device::getStatus, dto.getStatus());
        wrapper.like(StrUtil.isNotBlank(dto.getCompany()), Device::getCompany, dto.getCompany());
        //基础条件
        wrapper.eq(Device::getIsDeleted, Boolean.FALSE);
        wrapper.orderByDesc(Device::getId);
        return wrapper;
    }

    private void complete(IPage<DeviceVo> convert) {
        List<DeviceVo> records = convert.getRecords();
        if (records != null && records.size() > 0) {
            List<Scene> scenelist = new ArrayList<>();
            List<UserLib> userliblist = new ArrayList<>();
            List<Tenant> tenantlist = new ArrayList<>();

            List<Long> tenantIds = records.stream().filter(item -> item.getTenantId() != null).map(DeviceVo::getTenantId).collect(Collectors.toList());
            if (tenantIds != null && tenantIds.size() > 0) {
                LambdaQueryWrapper<Tenant> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Tenant::getIsDeleted, Boolean.FALSE);
                tenantlist = tenantMapper.selectList(wrapper);
            }

            List<Long> sceneIds = records.stream().filter(item -> item.getSceneId() != null).map(DeviceVo::getSceneId).collect(Collectors.toList());
            if (sceneIds != null && sceneIds.size() > 0) {
                LambdaQueryWrapper<Scene> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Scene::getIsDeleted, Boolean.FALSE);
                wrapper.in(Scene::getId, sceneIds);
                scenelist = sceneMapper.selectList(wrapper);
            }
            List<Long> userLibIds = records.stream().filter(item -> item.getUserLibId() != null).map(DeviceVo::getUserLibId).collect(Collectors.toList());
            if (userLibIds != null && userLibIds.size() > 0) {
                LambdaQueryWrapper<UserLib> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(UserLib::getIsDeleted, Boolean.FALSE);
                wrapper.in(UserLib::getId, userLibIds);
                userliblist = userLibMapper.selectList(wrapper);
            }
            Map<Long, Scene> sceneMap = scenelist.stream().collect(Collectors.toMap(Scene::getId, a -> a, (k1, k2) -> k1));
            Map<Long, UserLib> userLibMap = userliblist.stream().collect(Collectors.toMap(UserLib::getId, a -> a, (k1, k2) -> k1));
            Map<Long, Tenant> tenantMap = tenantlist.stream().collect(Collectors.toMap(Tenant::getId, a -> a, (k1, k2) -> k1));
            records.stream().forEach(item -> {
                if (item.getTenantId() != null) {
                    Tenant tenant = tenantMap.get(item.getTenantId());
                    if (tenant != null) {
                        item.setTenantMachineAppId(tenant.getMachineAppId());
                        item.setTenantName(tenant.getName());
                        item.setTenantServiceAddress(tenant.getServiceAddress());
                        item.setTenantServiceAppId(tenant.getServiceAppId());
                    }
                }
                if (item.getSceneId() != null) {
                    Scene scene = sceneMap.get(item.getSceneId());
                    if (scene != null) {
                        item.setSceneName(scene.getSceneName());
                        item.setTrade(scene.getTrade());
                    }
                }
                if (item.getUserLibId() != null) {
                    UserLib userLib = userLibMap.get(item.getUserLibId());
                    if (userLib != null) {
                        item.setUserLibName(userLib.getUserLibName());
                        item.setGroupId(userLib.getGroupId());
                    }
                }
            });
            convert.setRecords(records);
        }
    }

}
