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

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.RestCode;
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.AmpeDeviceSearch;
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.IotDeviceConfigService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author shisl
 * @package cn.hanghui.outapi.platform.tenant.service.impl
 * @class IotDeviceConfigServiceImpl
 * @date 2023/12/5 下午1:29
 * @description
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class IotDeviceConfigServiceImpl extends BaseService implements IotDeviceConfigService {
    private final IotDeviceConfigMapper iotDeviceConfigMapper;
    private final PurchaserMapper purchaserMapper;
    private final ApplicationTypeMapper applicationTypeMapper;
    private final DeviceModelMapper deviceModelMapper;
    private final AmpeMapper ampeMapper;
    private final TenantMapper tenantMapper;
    private final UserLibMapper userLibMapper;
    private final SceneMapper sceneMapper;
    private final CommonImpl commonImpl;
    private final AccountAuthConfigMapper accountAuthConfigMapper;


    @Override
    public RestResult<Boolean> add(IotDeviceConfigDto dto) {
        this.checkDto(dto);

        if (dto.getIotDeviceConfigId() == null) {
            LambdaQueryWrapper<IotDeviceConfig> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(IotDeviceConfig::getSn, dto.getSn()).eq(IotDeviceConfig::getIsDeleted, Boolean.FALSE);
            IotDeviceConfig config = iotDeviceConfigMapper.selectOne(wrapper);
            ClassUtil.throwBusinessException(ObjectUtil.isNotNull(config), "设备号已存在");
            config = BeanUtil.copyProperties(dto, IotDeviceConfig.class);
            iotDeviceConfigMapper.insert(config);
        } else {
            IotDeviceConfig config = iotDeviceConfigMapper.selectById(dto.getIotDeviceConfigId());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(config), "数据不存在");
            ClassUtil.throwBusinessException(!config.getSn().equals(dto.getSn()), "设备号不可修改");
            BeanUtil.copyProperties(dto, config);
            iotDeviceConfigMapper.updateById(config);
        }
        return RestResult.ok(true);
    }

    private void checkDto(IotDeviceConfigDto dto) {
        //购买方
        Purchaser purchaser = purchaserMapper.selectById(dto.getPurchaserId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(purchaser), "购买方不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(purchaser.getIsDeleted()), "购买方已删除");
        //应用类型
        ApplicationType applicationType = applicationTypeMapper.selectById(dto.getApplicationTypeId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(applicationType), "应用类型不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(applicationType.getIsDeleted()), "购买方已删除");
        //设备类型（硬件）
        DeviceModel deviceModelHardware = deviceModelMapper.selectById(dto.getDeviceModelHardwareId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelHardware), "设备类型（硬件）不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelHardware.getIsDeleted()), "设备类型（硬件）已删除");
        //设备类型（环境）
        DeviceModel deviceModelEnvironment = deviceModelMapper.selectById(dto.getDeviceModelEnvironmentId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelEnvironment), "设备类型（环境）不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelEnvironment.getIsDeleted()), "设备类型（环境）已删除");
        //ampe平台
        Ampe ampe = ampeMapper.selectById(dto.getAmpeId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(ampe), "ampe平台不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(ampe.getIsDeleted()), "ampe平台已删除");
        //服务商平台
        if (ObjectUtil.isNotNull(dto.getTenantId())) {
            Tenant tenant = tenantMapper.selectById(dto.getTenantId());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(tenant), "服务商平台不存在");
            ClassUtil.throwBusinessException(ObjectUtil.isNull(tenant.getIsDeleted()), "服务商平台已删除");
        }
        //用户库
        if (ObjectUtil.isNotNull(dto.getUserLibId())) {
            UserLib userLib = userLibMapper.selectById(dto.getUserLibId());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(userLib), "用户库不存在");
            ClassUtil.throwBusinessException(ObjectUtil.isNull(userLib.getIsDeleted()), "用户库已删除");
        }
        //场景
        if (ObjectUtil.isNotNull(dto.getSceneId())) {
            Scene scene = sceneMapper.selectById(dto.getSceneId());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(scene), "场景不存在");
            ClassUtil.throwBusinessException(ObjectUtil.isNull(scene.getIsDeleted()), "场景已删除");
        }
        //模式
        if (ObjectUtil.isNotNull(dto.getMode())) {
            ModeEnum modeEnum = ModeEnum.getEnumByCode(dto.getMode());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(modeEnum), "模式不存在");
        }

        //系统类型
        SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(dto.getSystemTypeCode());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(systemTypeEnum), "系统类型不存在");
        //摄像头类型
        CameraTypeEnum cameraTypeEnum = CameraTypeEnum.getEnumByCode(dto.getCameraType());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(cameraTypeEnum), "摄像头类型不存在");
        //摄像头品牌
        CameraBrandEnum cameraBrandEnum = CameraBrandEnum.getEnumByCode(dto.getCameraBrand());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(cameraBrandEnum), "摄像品牌不存在");

        //身份证阅读器品牌
        if (Preconditions.isNotBlank(dto.getIdCardReaderBrand())) {
            IdCardReaderBrandEnum idCardReaderBrandEnum = IdCardReaderBrandEnum.queryEnumByCode(dto.getIdCardReaderBrand());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(idCardReaderBrandEnum), RestCode.FAIL.getCode(), "身份证阅读器品牌不存在");
        }

    }

    @Override
    public RestResult<IPage<IotDeviceConfigVo>> page(IotDeviceConfigPageDto dto) {
        LambdaQueryWrapper<IotDeviceConfig> wrapper = this.getWrapper(dto);
        Page<IotDeviceConfig> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        IPage<IotDeviceConfig> iPage = iotDeviceConfigMapper.selectPage(page, wrapper);

        Map<Long, Purchaser> purchaserMap = commonImpl.getPurchaserMap(iPage, IotDeviceConfig::getPurchaserId);
        Map<Long, ApplicationType> applicationTypeMap = commonImpl.getApplicationTypeMap(iPage, IotDeviceConfig::getApplicationTypeId);
        Map<Long, DeviceModel> deviceModelHardwareMap = commonImpl.getDeviceModelMap(iPage, IotDeviceConfig::getDeviceModelHardwareId);
        Map<Long, DeviceModel> deviceModelEnvironmentMap = commonImpl.getDeviceModelMap(iPage, IotDeviceConfig::getDeviceModelEnvironmentId);
        Map<Long, Ampe> ampeMap = commonImpl.getAmpeMap(iPage, IotDeviceConfig::getAmpeId);
        Map<Long, Tenant> tenantMap = commonImpl.getTenantMap(iPage, IotDeviceConfig::getTenantId);
        Map<Long, UserLib> userLibMap = commonImpl.getUserLibMap(iPage, IotDeviceConfig::getUserLibId);
        Map<Long, Scene> sceneMap = commonImpl.getSceneMap(iPage, IotDeviceConfig::getSceneId);

        IPage<IotDeviceConfigVo> convert = iPage.convert(t -> {
            IotDeviceConfigVo item = BeanUtil.copyProperties(t, IotDeviceConfigVo.class);
            item.setIotDeviceConfigId(t.getId());
            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());
            }
            if (ampeMap.containsKey(t.getAmpeId())) {
                item.setAmpeName(ampeMap.get(t.getAmpeId()).getAmpeName());
            }
            if (tenantMap.containsKey(t.getTenantId())) {
                item.setTenantName(tenantMap.get(t.getTenantId()).getName());
            }
            if (userLibMap.containsKey(t.getUserLibId())) {
                item.setUserLibName(userLibMap.get(t.getUserLibId()).getUserLibName());
            }
            if (sceneMap.containsKey(t.getSceneId())) {
                item.setSceneName(sceneMap.get(t.getSceneId()).getSceneName());
            }
            SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(t.getSystemTypeCode());
            if (ObjectUtil.isNotNull(systemTypeEnum)) {
                item.setSystemType(systemTypeEnum.getDesc());
            }
            return item;
        });
        return RestResult.ok(convert);
    }

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

    @Override
    public RestResult<Boolean> del(Long id) {
        IotDeviceConfig config = iotDeviceConfigMapper.selectById(id);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(config), "数据不存在或已删除");
        iotDeviceConfigMapper.deleteById(config);
        return RestResult.ok(Boolean.TRUE);
    }

    @Override
    public RestResult<Boolean> empower(Long iotDeviceConfigId) {
        IotDeviceConfig config = iotDeviceConfigMapper.selectById(iotDeviceConfigId);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(config), "数据不存在或已删除");
        config.setStatus(true);
        iotDeviceConfigMapper.updateById(config);
        return RestResult.ok(true);
    }

    @Override
    public RestResult<Boolean> cancelEmpower(Long iotDeviceConfigId) {
        IotDeviceConfig config = iotDeviceConfigMapper.selectById(iotDeviceConfigId);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(config), "数据不存在或已删除");
        config.setStatus(false);
        iotDeviceConfigMapper.updateById(config);
        return RestResult.ok(true);
    }

    @Override
    public IotDeviceAppletConfigVo snConfig(IotDeviceAppletConfigDto dto) {
        LambdaQueryWrapper<IotDeviceConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IotDeviceConfig::getSn, dto.getSn()).eq(IotDeviceConfig::getIsDeleted, Boolean.FALSE);
        IotDeviceConfig config = iotDeviceConfigMapper.selectOne(wrapper);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(config), "数据不存在或已删除");
        ClassUtil.throwBusinessException(!config.getStatus(), "设备商户平台未授权");
        IotDeviceAppletConfigVo configVo = BeanUtil.copyProperties(config, IotDeviceAppletConfigVo.class);
        configVo.setIdNumberReaderType(config.getIdCardReaderBrand());
        this.dataInsert(configVo, config);
        return configVo;
    }

    private void dataInsert(IotDeviceAppletConfigVo configVo, IotDeviceConfig config) {
        //购买方
        if (ObjectUtil.isNotNull(config.getPurchaserId())) {
            Purchaser purchaser = purchaserMapper.selectById(config.getPurchaserId());
            if (ObjectUtil.isNotNull(purchaser)) {
                configVo.setCompanyName(purchaser.getCompanyName());
            }
        }
        //应用类型
        if (ObjectUtil.isNotNull(config.getApplicationTypeId())) {
            ApplicationType applicationType = applicationTypeMapper.selectById(config.getApplicationTypeId());
            if (ObjectUtil.isNotNull(applicationType)) {
                configVo.setApplicationType(applicationType.getApplicationType());
            }
        }
        //设备类型（硬件）
        if (ObjectUtil.isNotNull(config.getDeviceModelHardwareId())) {
            DeviceModel deviceModelHardware = deviceModelMapper.selectById(config.getDeviceModelHardwareId());
            if (ObjectUtil.isNotNull(deviceModelHardware)) {
                configVo.setDeviceModelHardware(deviceModelHardware.getDeviceModel());
            }
        }
        //设备类型（环境）
        if (ObjectUtil.isNotNull(config.getDeviceModelEnvironmentId())) {
            DeviceModel deviceModelEnvironment = deviceModelMapper.selectById(config.getDeviceModelEnvironmentId());
            if (ObjectUtil.isNotNull(deviceModelEnvironment)) {
                configVo.setDeviceModelEnvironment(deviceModelEnvironment.getDeviceModel());
            }
        }

        //ampe平台
        Ampe ampe = ampeMapper.selectById(config.getAmpeId());
        if (ObjectUtil.isNotNull(ampe)) {
            configVo.setAmpeName(ampe.getAmpeName());
            configVo.setProductId(ampe.getProductId());
            configVo.setAmpeAppid(ampe.getHostAppId());
            configVo.setMiniProgramAppid(ampe.getAppId());
            configVo.setAppName(ampe.getAppName());

            Long productId = Long.valueOf(ampe.getProductId()); // 门户设备产品注册得到的productId
            String deviceId = config.getSn(); // 设备号
            String encodeContent = productId + "_" + deviceId;
            // 获取签名
            try {
                String signature = AlipaySignature.rsa256Sign(encodeContent, getKey8PrivateKey(ampe.getHostAppId()), "UTF-8");
                configVo.setSignature(signature);
            } catch (AlipayApiException e) {
            }
        } else {
            try {
                Long productId = Long.valueOf(config.getProductId()); // 门户设备产品注册得到的productId
                String deviceId = config.getSn(); // 一个产品下的唯一设备识别号,厂商自定义,建议使用SN等设备标识
                String encodeContent = productId + "_" + deviceId;
                // 获取签名
                String signature = AlipaySignature.rsa256Sign(encodeContent, getKey8PrivateKey(config.getHostAppId()), "UTF-8");
                // 其它业务逻辑
                configVo.setMiniProgramAppid(config.getAppId());
                configVo.setSn(config.getSn());
                configVo.setAmpeAppid(config.getHostAppId());
                configVo.setProductId(config.getProductId());
                configVo.setSignature(signature);
                configVo.setAppName(config.getAppName());
            } catch (AlipayApiException e) {

            }

        }
        //服务商平台
        if (ObjectUtil.isNotNull(config.getTenantId())) {
            Tenant tenant = tenantMapper.selectById(config.getTenantId());
            if (ObjectUtil.isNotNull(tenant)) {
                configVo.setTenantName(tenant.getName());
                configVo.setMachineAppId(tenant.getMachineAppId());
                configVo.setServiceAppId(tenant.getServiceAppId());
                configVo.setServiceAddress(tenant.getServiceAddress());
                configVo.setAppAuthToken(tenant.getAppAuthToken());
                configVo.setAppAuthTokenStatus(tenant.getAppAuthTokenStatus());
                configVo.setThirdAuth(tenant.getThirdAuth());
                configVo.setAbcpAppId(tenant.getMachineAppId());
            }
        }

        //用户库
        if (ObjectUtil.isNotNull(config.getUserLibId())) {
            UserLib userLib = userLibMapper.selectById(config.getUserLibId());
            if (ObjectUtil.isNotNull(userLib)) {
                configVo.setUserLibName(userLib.getUserLibName());
                configVo.setGroupId(userLib.getGroupId());
            }
        }

        //场景
        if (ObjectUtil.isNotNull(config.getSceneId())) {
            Scene scene = sceneMapper.selectById(config.getSceneId());
            if (ObjectUtil.isNotNull(scene)) {
                configVo.setSceneName(scene.getSceneName());
                configVo.setTrade(scene.getTrade());
            }
        }

        //模式
        ModeEnum modeEnum = ModeEnum.getEnumByCode(config.getMode());
        if (ObjectUtil.isNotNull(modeEnum)) {
            configVo.setMode(modeEnum.getDesc());
        }
        //系统类型
        SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(config.getSystemTypeCode());
        if (ObjectUtil.isNotNull(systemTypeEnum)) {
            configVo.setSystemType(systemTypeEnum.getDesc());
        }
    }

    @Override
    public Boolean updateConfig(IotDeviceAppletUpdateConfigDto dto) {
        LambdaQueryWrapper<IotDeviceConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IotDeviceConfig::getSn, dto.getSn()).eq(IotDeviceConfig::getIsDeleted, Boolean.FALSE);
        IotDeviceConfig config = iotDeviceConfigMapper.selectOne(wrapper);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(config), "数据不存在或已删除");
        ClassUtil.throwBusinessException(!config.getStatus(), "设备商户平台未授权");
        //摄像头类型
        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.getIdCardReaderBrand())) {
            IdCardReaderBrandEnum idCardReaderBrandEnum = IdCardReaderBrandEnum.queryEnumByCode(dto.getIdCardReaderBrand());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(idCardReaderBrandEnum), "身份证阅读器品牌不存在");
        }

        BeanUtil.copyProperties(dto, config);
        iotDeviceConfigMapper.updateById(config);
        return Boolean.TRUE;
    }

    @Override
    public RestResult<IPage<IotDeviceConfigVo>> page(AmpeDeviceSearch 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.getHhAromeSwitch()) || !config.getHhAromeSwitch() || Preconditions.isBlank(config.getPurchaserId())) {
            throw new BusinessException("禁止访问该资源");
        }
//        List<Long> ampeIds = commonImpl.getAuthAmpeIds(account);
//        List<Long> tenantIds = commonImpl.getAmpeTenantIds(account);
//        if (Preconditions.isBlank(ampeIds) && Preconditions.isBlank(tenantIds)) {
//            //throw new BusinessException("未找到访问资源");
//            return RestResult.ok(initEmptyPage());
//        }
//        if (Preconditions.isNotBlank(dto.getTenantId()) && !tenantIds.contains(dto.getTenantId())) {
//            throw new BusinessException("禁止访问该资源");
//        }
        LambdaQueryWrapper<IotDeviceConfig> wrapper = new LambdaQueryWrapper<>();
        //查询的传参条件
        wrapper.like(StrUtil.isNotBlank(dto.getSn()), IotDeviceConfig::getSn, dto.getSn());
        wrapper.eq(Preconditions.isNotBlank(dto.getAmpeId()), IotDeviceConfig::getAmpeId, dto.getAmpeId());
        wrapper.eq(Preconditions.isNotBlank(dto.getTenantId()), IotDeviceConfig::getTenantId, dto.getTenantId());
        wrapper.eq(IotDeviceConfig::getPurchaserId, config.getPurchaserId());
        //基础条件
        wrapper.eq(IotDeviceConfig::getIsDeleted, Boolean.FALSE);
        wrapper.orderByDesc(IotDeviceConfig::getId);
        Page<IotDeviceConfig> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        IPage<IotDeviceConfig> iPage = iotDeviceConfigMapper.selectPage(page, wrapper);
        Map<Long, Ampe> ampeMap = commonImpl.getAmpeMap(iPage, IotDeviceConfig::getAmpeId);
        Map<Long, Tenant> tenantMap = commonImpl.getTenantMap(iPage, IotDeviceConfig::getTenantId);
        IPage<IotDeviceConfigVo> convert = iPage.convert(t -> {
            IotDeviceConfigVo item = BeanUtil.copyProperties(t, IotDeviceConfigVo.class);
            item.setIotDeviceConfigId(t.getId());
            if (ampeMap.containsKey(t.getAmpeId())) {
                item.setAmpeName(ampeMap.get(t.getAmpeId()).getAmpeName());
            }
            if (tenantMap.containsKey(t.getTenantId())) {
                item.setTenantName(tenantMap.get(t.getTenantId()).getName());
            }
            return item;
        });
        return RestResult.ok(convert);
    }

    @Override
    public RestResult<Boolean> update(AmpeDeviceDto dto, Account account) {
        if (Preconditions.isBlank(dto.getIotDeviceConfigId())) {
            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.getHhAromeSwitch())
                || !authConfig.getHhAromeSwitch()) {
            throw new BusinessException("禁止修改该资源");
        }
        IotDeviceConfig config = iotDeviceConfigMapper.selectById(dto.getIotDeviceConfigId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(config), "数据不存在");
        checkAmpeConfig(dto, authConfig, account, config);
        iotDeviceConfigMapper.updateById(config);
        return RestResult.ok(Boolean.TRUE);
    }

    private void checkAmpeConfig(AmpeDeviceDto dto, AccountAuthConfig authConfig, Account account, IotDeviceConfig config) {
        List<Long> tenantIds = commonImpl.getAmpeTenantIds(account);
        if (Preconditions.isNotBlank(dto.getTenantId())
                && Preconditions.isNotBlank(authConfig.getDeviceConfig())
                && Preconditions.isNotBlank(tenantIds)
                && tenantIds.contains(dto.getTenantId())) {
            config.setTenantId(dto.getTenantId());
        }

        List<Long> ampeIds = commonImpl.getAuthAmpeIds(account);
        if (Preconditions.isNotBlank(dto.getAmpeId())
                && Preconditions.isNotBlank(authConfig.getDeviceConfig())
                && Preconditions.isNotBlank(ampeIds)
                && ampeIds.contains(dto.getAmpeId())) {
            config.setAmpeId(dto.getAmpeId());
        }

        List<String> systemConfig = authConfig.getSystemConfig();
        if (Preconditions.isNotBlank(dto.getAutoLaunch())
                && Preconditions.isNotBlank(systemConfig)
                && systemConfig.contains(SystemConfigEnum.AUTO_LAUNCH.getCode())) {
            config.setAutoLaunch(dto.getAutoLaunch());
        }
        if (Preconditions.isNotBlank(dto.getAutomaticEnterApplet())
                && Preconditions.isNotBlank(systemConfig)
                && systemConfig.contains(SystemConfigEnum.AUTOMATIC_ENTER_APPLET.getCode())) {
            config.setAutomaticEnterApplet(dto.getAutomaticEnterApplet());
        }
        if (Preconditions.isNotBlank(dto.getForbidPullDown())
                && Preconditions.isNotBlank(systemConfig)
                && systemConfig.contains(SystemConfigEnum.FORBID_PULL_DOWN.getCode())) {
            config.setForbidPullDown(dto.getForbidPullDown());
        }
        if (Preconditions.isNotBlank(dto.getHideNavigationBar())
                && Preconditions.isNotBlank(systemConfig)
                && systemConfig.contains(SystemConfigEnum.HIDE_NAVIGATION_BAR.getCode())) {
            config.setHideNavigationBar(dto.getHideNavigationBar());
        }
        if (Preconditions.isNotBlank(dto.getHomePageUrl())
                && Preconditions.isNotBlank(systemConfig)
                && systemConfig.contains(SystemConfigEnum.HOME_PAGE_URL.getCode())) {
            config.setHomePageUrl(dto.getHomePageUrl());
        }
        if (Preconditions.isNotBlank(dto.getStartPageUrl())
                && Preconditions.isNotBlank(systemConfig)
                && systemConfig.contains(SystemConfigEnum.START_PAGE_URL.getCode())) {
            config.setStartPageUrl(dto.getStartPageUrl());
        }
        if (Preconditions.isNotBlank(dto.getMpassword())
                && Preconditions.isNotBlank(systemConfig)
                && systemConfig.contains(SystemConfigEnum.M_PASSWORD.getCode())) {
            config.setMpassword(dto.getMpassword());
        }
        if (Preconditions.isNotBlank(dto.getVolume())
                && Preconditions.isNotBlank(systemConfig)
                && systemConfig.contains(SystemConfigEnum.VOLUME.getCode())) {
            config.setVolume(dto.getVolume());
        }
        List<String> useConfig = authConfig.getUseConfig();
        if (Preconditions.isNotBlank(dto.getExpirationDate())
                && Preconditions.isNotBlank(useConfig)
                && useConfig.contains(UseConfigEnum.USE_EXPIRATION_DATE.getCode())) {
            config.setExpirationDate(dto.getExpirationDate());
        }

    }
}
