package com.usky.cdi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usky.cdi.domain.CdiDefenseProject;
import com.usky.cdi.mapper.CdiDefenseProjectMapper;
import com.usky.cdi.service.CdiDefenseProjectService;
import com.usky.common.mybatis.core.AbstractCrudService;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 人防_工程表（人防工程基础信息及MQTT连接配置） 服务实现类
 * </p>
 *
 * @author fu
 * @since 2026-02-02
 */
@Service
public class CdiDefenseProjectServiceImpl extends AbstractCrudService<CdiDefenseProjectMapper, CdiDefenseProject> implements CdiDefenseProjectService {

    @Override
    public boolean tryConnectAndPublish(String brokerUrl, String username, String password, String payload, String tmpClientId) {

        MqttClient client = null;
        try {
            client = new MqttClient(brokerUrl, tmpClientId, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            options.setConnectionTimeout(3);
            options.setAutomaticReconnect(false);
            client.connect(options);

            return true;
        } catch (Exception e) {
            log.error("MQTT连接测试失败", e);
            return false;
        } finally {
            if (client != null) {
                try {
                    client.disconnect();
                } catch (Exception ignore) {
                }
                try {
                    client.close();
                } catch (Exception ignore) {
                }
                // 再加一行：把实例从缓存里强行踢掉
                // MqttClient.removeClient(client.getClientId());
            }
        }
    }

    @Override
    public CdiDefenseProject listByTenantId(Integer tenantId) {
        LambdaQueryWrapper<CdiDefenseProject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CdiDefenseProject::getTenantId, tenantId);
        return baseMapper.selectOne(queryWrapper);
    }
}
