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

import cn.hanghui.outapi.platform.common.entity.rest.RestCode;
import cn.hanghui.outapi.platform.common.entity.rest.RestResult;
import cn.hanghui.outapi.platform.common.utils.ClassUtil;
import cn.hanghui.outapi.platform.common.utils.Preconditions;
import cn.hanghui.outapi.platform.tenant.entity.dto.DeviceDefaultParam;
import cn.hanghui.outapi.platform.tenant.entity.dto.TenantDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.TenantVo;
import cn.hanghui.outapi.platform.tenant.entity.dto.hhculture.HhCultureDeviceDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.hhculture.HhCultureDeviceSearch;
import cn.hanghui.outapi.platform.tenant.entity.dto.hhculture.HhCultureDeviceTemplateDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.hhculture.HhCultureDeviceTemplateLessVo;
import cn.hanghui.outapi.platform.tenant.entity.dto.hhculture.HhCultureDeviceTemplateSearch;
import cn.hanghui.outapi.platform.tenant.entity.dto.hhculture.HhCultureDeviceTemplateVo;
import cn.hanghui.outapi.platform.tenant.entity.dto.hhculture.HhCultureDeviceUpdateMiniDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.hhculture.HhCultureDeviceVo;
import cn.hanghui.outapi.platform.tenant.entity.enums.*;
import cn.hanghui.outapi.platform.tenant.entity.po.ApplicationType;
import cn.hanghui.outapi.platform.tenant.entity.po.DeviceModel;
import cn.hanghui.outapi.platform.tenant.entity.po.HhCultureDevice;
import cn.hanghui.outapi.platform.tenant.entity.po.HhCultureDeviceTemplate;
import cn.hanghui.outapi.platform.tenant.entity.po.Purchaser;
import cn.hanghui.outapi.platform.tenant.entity.po.Tenant;
import cn.hanghui.outapi.platform.tenant.entity.po.UserLib;
import cn.hanghui.outapi.platform.tenant.mapper.ApplicationTypeMapper;
import cn.hanghui.outapi.platform.tenant.mapper.DeviceModelMapper;
import cn.hanghui.outapi.platform.tenant.mapper.HhCultureDeviceMapper;
import cn.hanghui.outapi.platform.tenant.mapper.HhCultureDeviceTemplateMapper;
import cn.hanghui.outapi.platform.tenant.mapper.PurchaserMapper;
import cn.hanghui.outapi.platform.tenant.mapper.TenantMapper;
import cn.hanghui.outapi.platform.tenant.mapper.UserLibMapper;
import cn.hanghui.outapi.platform.tenant.service.HHCultureDeviceService;
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.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
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
 * @class HHCultureDevice
 * @date 2024/7/19 上午10:50
 * @description
 */
@Slf4j
@Service
public class HHCultureDeviceServiceImpl implements HHCultureDeviceService {

    @Resource
    private HhCultureDeviceTemplateMapper hhCultureDeviceTemplateMapper;

    @Resource
    private HhCultureDeviceMapper hhCultureDeviceMapper;

    @Resource
    private DeviceModelMapper deviceModelMapper;

    @Resource
    private CommonImpl commonImpl;

    @Resource
    private ApplicationTypeMapper applicationTypeMapper;

    @Resource
    private PurchaserMapper purchaserMapper;

    @Resource
    private TenantMapper tenantMapper;

    @Resource
    private UserLibMapper userLibMapper;


    @Override
    public Boolean templateEdit(HhCultureDeviceTemplateDto dto) {
        checkTemplateDto(dto);
        Long templateId = dto.getDeviceTemplateId();
        if (templateId == null) {
            HhCultureDeviceTemplate template = BeanUtil.copyProperties(dto, HhCultureDeviceTemplate.class);
            hhCultureDeviceTemplateMapper.insert(template);
        } else {
            HhCultureDeviceTemplate base = hhCultureDeviceTemplateMapper.selectById(templateId);
            ClassUtil.throwBusinessException(ObjectUtil.isNull(base), RestCode.FAIL.getCode(), "模版不存在");
            BeanUtil.copyProperties(dto, base);
            hhCultureDeviceTemplateMapper.updateById(base);
        }
        return true;
    }

    private void checkTemplateDto(HhCultureDeviceTemplateDto dto) {
        //应用类型
        if (Preconditions.isNotBlank(dto.getApplicationTypeId())) {
            ApplicationType applicationType = applicationTypeMapper.selectById(dto.getApplicationTypeId());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(applicationType), RestCode.FAIL.getCode(), "应用类型不存在");
            ClassUtil.throwBusinessException(ObjectUtil.isNull(applicationType.getIsDeleted()), RestCode.FAIL.getCode(), "应用类型已删除");
        }
        //设备类型（硬件）
        if (Preconditions.isNotBlank(dto.getDeviceModelHardwareId())) {
            DeviceModel deviceModelHardware = deviceModelMapper.selectById(dto.getDeviceModelHardwareId());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelHardware), RestCode.FAIL.getCode(), "设备类型（硬件）不存在");
            ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelHardware.getIsDeleted()), RestCode.FAIL.getCode(), "设备类型（硬件）已删除");
        }
        //设备类型（环境）
        if (Preconditions.isNotBlank(dto.getDeviceModelEnvironmentId())) {
            DeviceModel deviceModelEnvironment = deviceModelMapper.selectById(dto.getDeviceModelEnvironmentId());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelEnvironment), RestCode.FAIL.getCode(), "设备类型（环境）不存在");
            ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelEnvironment.getIsDeleted()), RestCode.FAIL.getCode(), "设备类型（环境）已删除");
        }
        //系统类型
        if (Preconditions.isNotBlank(dto.getSystemTypeCode())) {
            SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(dto.getSystemTypeCode());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(systemTypeEnum), RestCode.FAIL.getCode(), "系统类型不存在");
        }

    }

    @Override
    public List<HhCultureDeviceTemplateLessVo> templateList() {
        LambdaQueryWrapper<HhCultureDeviceTemplate> wrapper = new LambdaQueryWrapper<>();
        //查询的基础条件
        wrapper.select(HhCultureDeviceTemplate::getId, HhCultureDeviceTemplate::getTemplateName);
        wrapper.eq(HhCultureDeviceTemplate::getIsDeleted, Boolean.FALSE);
        wrapper.orderByDesc(HhCultureDeviceTemplate::getId);
        List<HhCultureDeviceTemplate> templates = hhCultureDeviceTemplateMapper.selectList(wrapper);
        return templates.stream().map(p -> new HhCultureDeviceTemplateLessVo()
                .setDeviceTemplateId(p.getId())
                .setTemplateName(p.getTemplateName())).collect(Collectors.toList());
    }

    @Override
    public IPage<HhCultureDeviceTemplateVo> templatePage(HhCultureDeviceTemplateSearch dto) {
        Page<HhCultureDeviceTemplate> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        LambdaQueryWrapper<HhCultureDeviceTemplate> wrapper = this.getWrapper(dto);
        IPage<HhCultureDeviceTemplate> iPage = hhCultureDeviceTemplateMapper.selectPage(page, wrapper);
        Map<Long, ApplicationType> applicationTypeMap = commonImpl.getApplicationTypeMap(iPage, HhCultureDeviceTemplate::getApplicationTypeId);
        Map<Long, DeviceModel> deviceModelHardwareMap = commonImpl.getDeviceModelMap(iPage, HhCultureDeviceTemplate::getDeviceModelHardwareId);
        Map<Long, DeviceModel> deviceModelEnvironmentMap = commonImpl.getDeviceModelMap(iPage, HhCultureDeviceTemplate::getDeviceModelEnvironmentId);
        Map<Long, Tenant> tenantMap = commonImpl.getTenantMap(iPage, HhCultureDeviceTemplate::getTenantId);
        Map<Long, UserLib> userLibMap = commonImpl.getUserLibMap(iPage, HhCultureDeviceTemplate::getUserLibId);
        return iPage.convert(t -> {
            HhCultureDeviceTemplateVo item = BeanUtil.copyProperties(t, HhCultureDeviceTemplateVo.class);
            item.setDeviceTemplateId(t.getId());
            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 (tenantMap.containsKey(t.getTenantId())) {
                item.setTenantName(tenantMap.get(t.getTenantId()).getName());
            }
            if (userLibMap.containsKey(t.getUserLibId())) {
                item.setUserLibName(userLibMap.get(t.getUserLibId()).getUserLibName());
            }

            SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(t.getSystemTypeCode());
            if (ObjectUtil.isNotNull(systemTypeEnum)) {
                item.setSystemType(systemTypeEnum.getDesc());
            }

            return item;
        });
    }

    private LambdaQueryWrapper<HhCultureDeviceTemplate> getWrapper(HhCultureDeviceTemplateSearch dto) {
        LambdaQueryWrapper<HhCultureDeviceTemplate> wrapper = new LambdaQueryWrapper<>();
        //查询的传参条件
        wrapper.eq(ObjectUtil.isNotNull(dto.getDeviceTemplateId()), HhCultureDeviceTemplate::getId, dto.getDeviceTemplateId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getApplicationTypeId()), HhCultureDeviceTemplate::getApplicationTypeId, dto.getApplicationTypeId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getDeviceModelHardwareId()), HhCultureDeviceTemplate::getDeviceModelHardwareId, dto.getDeviceModelHardwareId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getDeviceModelEnvironmentId()), HhCultureDeviceTemplate::getDeviceModelEnvironmentId, dto.getDeviceModelEnvironmentId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getSystemTypeCode()), HhCultureDeviceTemplate::getSystemTypeCode, dto.getSystemTypeCode());
        wrapper.eq(ObjectUtil.isNotNull(dto.getTenantId()), HhCultureDeviceTemplate::getTenantId, dto.getTenantId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getUserLibId()), HhCultureDeviceTemplate::getUserLibId, dto.getUserLibId());
        //查询的基础条件
        wrapper.eq(HhCultureDeviceTemplate::getIsDeleted, Boolean.FALSE);
        wrapper.orderByDesc(HhCultureDeviceTemplate::getId);
        return wrapper;
    }

    @Override
    public Boolean templateDelete(Long id) {
        HhCultureDeviceTemplate template = hhCultureDeviceTemplateMapper.selectById(id);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(template), RestCode.FAIL.getCode(), "模版不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(template.getIsDeleted()), RestCode.FAIL.getCode(), "模版已删除");
        hhCultureDeviceTemplateMapper.deleteById(id);
        return Boolean.TRUE;
    }

    @Override
    public HhCultureDeviceTemplateVo templateDetail(Long deviceTemplateId) {
        HhCultureDeviceTemplate deviceTemplate = hhCultureDeviceTemplateMapper.selectById(deviceTemplateId);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceTemplate), "iot模版不存在");
        ClassUtil.throwBusinessException(deviceTemplate.getIsDeleted(), "iot模版已删除");
        HhCultureDeviceTemplateVo templateVo = BeanUtil.copyProperties(deviceTemplate, HhCultureDeviceTemplateVo.class);
        templateVo.setDeviceTemplateId(deviceTemplate.getId());
        return templateVo;
    }

    @Override
    public RestResult<Boolean> add(HhCultureDeviceDto dto) {
        if (dto.getSn() == null) {
            return RestResult.error("参数有误");
        }

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

        HhCultureDevice device = null;
        if (dto.getId() != null) {
            device = hhCultureDeviceMapper.selectById(dto.getId());
            if (device == null || device.getIsDeleted() == null || device.getIsDeleted()) {
                return RestResult.error("数据不存在或已删除");
            }
        } else {
            device = new HhCultureDevice();
            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) {
            hhCultureDeviceMapper.updateById(device);
        } else {
            hhCultureDeviceMapper.insert(device);
        }
        return RestResult.ok(Boolean.TRUE);
    }

    @Override
    public RestResult<IPage<HhCultureDeviceVo>> page(HhCultureDeviceSearch dto) {
        LambdaQueryWrapper<HhCultureDevice> wrapper = this.getDeviceWrapper(dto);
        Page<HhCultureDevice> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        IPage<HhCultureDevice> iPage = hhCultureDeviceMapper.selectPage(page, wrapper);

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

        IPage<HhCultureDeviceVo> convert = iPage.convert(t -> {
            HhCultureDeviceVo item = BeanUtil.copyProperties(t, HhCultureDeviceVo.class);
            item.setZoloConfig(t.getZoloConfig());
            item.setTenantId(t.getTenantId());
            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> del(Long deviceId) {
        HhCultureDevice device = hhCultureDeviceMapper.selectById(deviceId);
        if (device != null && device.getIsDeleted() != null && !device.getIsDeleted()) {
            hhCultureDeviceMapper.deleteById(device);
        }
        return RestResult.ok(Boolean.TRUE);
    }

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

    @Override
    public RestResult<List<TenantVo>> snConfig(TenantDto dto) {
        List<HhCultureDevice> devices = hhCultureDeviceMapper.selectList(Wrappers.lambdaQuery(HhCultureDevice.class).eq(HhCultureDevice::getStatus, Boolean.TRUE).isNotNull(HhCultureDevice::getTenantId).eq(HhCultureDevice::getSn, dto.getSn()).eq(HhCultureDevice::getIsDeleted, Boolean.FALSE));
        if (devices == null || devices.size() == 0) {
            return RestResult.error("设备商户平台未授权");
        }
        List<Long> tenantIds = devices.stream().filter(item -> item.getTenantId() != null).map(HhCultureDevice::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<HhCultureDevice> devices, List<TenantVo> vos) {

        List<UserLib> userliblist = new ArrayList<>();
        List<Long> userLibIds = devices.stream().filter(item -> item.getUserLibId() != null).map(HhCultureDevice::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, HhCultureDevice> deviceMap = devices.stream().collect(Collectors.toMap(HhCultureDevice::getTenantId, 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 -> {
            HhCultureDevice device = deviceMap.get(item.getId());
            if (device != null) {
                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());
//                        //弹性模式
//                        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, HhCultureDevice device) {
        BeanUtil.copyProperties(device, item, "id");
    }

    @Override
    public RestResult<Boolean> updateConfig(HhCultureDeviceUpdateMiniDto dto) {
        if (dto.getSn() == null) {
            return RestResult.error("参数有误");
        }
        List<HhCultureDevice> devices = hhCultureDeviceMapper.selectList(Wrappers.lambdaQuery(HhCultureDevice.class).eq(HhCultureDevice::getSn, dto.getSn()).eq(HhCultureDevice::getIsDeleted, Boolean.FALSE));
        if (devices == null || devices.size() == 0) {
            return RestResult.error("数据不存在或已删除");
        }
        HhCultureDevice device = devices.get(0);
        device.setUpdateTime(new Date());
        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.getUseLinkage() != null) {
            device.setUseLinkage(dto.getUseLinkage());
        }
        if (StrUtil.isNotBlank(dto.getUseSerialPort())) {
            device.setUseSerialPort(dto.getUseSerialPort());
        }
        if (StrUtil.isNotBlank(dto.getDoorSerialPort())) {
            device.setDoorSerialPort(dto.getDoorSerialPort());
        }
        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());
        }
        if (StrUtil.isNotBlank(dto.getHeartTrackingUrl())) {
            device.setHeartTrackingUrl(dto.getHeartTrackingUrl());
        }
        if (StrUtil.isNotBlank(dto.getTransitPushUrl())) {
            device.setTransitPushUrl(dto.getTransitPushUrl());
        }
        if (dto.getAutoLaunch() != null) {
            device.setAutoLaunch(dto.getAutoLaunch());
        }
        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());
            }
        }
        if (Preconditions.isNotBlank(dto.getManualIn())) {
            device.setManualIn(dto.getManualIn());
        }
        if (Preconditions.isNotBlank(dto.getManualInParams())) {
            device.setManualInParams(dto.getManualInParams());
        }
        if (ObjectUtil.isNotNull(dto.getIdCardReaderBrand())) {
            IdCardReaderBrandEnum idCardReaderBrandEnum = IdCardReaderBrandEnum.queryEnumByCode(dto.getIdCardReaderBrand());
            if (ObjectUtil.isNotNull(idCardReaderBrandEnum)) {
                device.setIdCardReaderBrand(dto.getIdCardReaderBrand());
            }
        }
        if (Preconditions.isNotBlank(dto.getAnalysisPhoto())) {
            device.setAnalysisPhoto(dto.getAnalysisPhoto());
        }
        if (Preconditions.isNotBlank(dto.getAnalysisFingerprint())) {
            device.setAnalysisFingerprint(dto.getAnalysisFingerprint());
        }
        if (Preconditions.isNotBlank(dto.getIdCardInterval())) {
            if (dto.getIdCardInterval() >= 0 && dto.getIdCardInterval() <= 20) {
                device.setIdCardInterval(dto.getIdCardInterval());
            }
        }
        device.setMpassword(dto.getMpassword());
        hhCultureDeviceMapper.updateById(device);
        return RestResult.ok(Boolean.TRUE);
    }

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

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

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

            List<Long> tenantIds = records.stream().filter(item -> item.getTenantId() != null).map(HhCultureDeviceVo::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> userLibIds = records.stream().filter(item -> item.getUserLibId() != null).map(HhCultureDeviceVo::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, 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.getUserLibId() != null) {
                    UserLib userLib = userLibMap.get(item.getUserLibId());
                    if (userLib != null) {
                        item.setUserLibName(userLib.getUserLibName());
                        item.setGroupId(userLib.getGroupId());
                    }
                }
            });
            convert.setRecords(records);
        }
    }

    private void handleParams(HhCultureDevice device, HhCultureDeviceDto 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 (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.getIc15693ReaderBrand());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(readerBrandEnum), "Ic15693阅读器品牌不存在");
        }
        device.setUpdateTime(new Date());
        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());
        }

    }

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

}
