package com.zhongshu.card.server.core.service.mqtt;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.JsonObject;
import com.zhongshu.card.client.model.mqtt.MqttConfigModel;
import com.zhongshu.card.client.model.mqtt.SendMessageModel;
import com.github.microservice.net.ResultContent;
import com.zhongshu.card.client.type.ArtemisType;
import com.zhongshu.card.server.core.dao.mqtt.ArtemisMessageDao;
import com.zhongshu.card.server.core.dao.mqtt.MqttConfigDao;
import com.zhongshu.card.server.core.dao.org.UserCountDao;
import com.zhongshu.card.server.core.domain.mqtt.ArtemisMessage;
import com.zhongshu.card.server.core.domain.mqtt.MqttConfig;
import com.zhongshu.card.server.core.domain.org.UserAccount;
import com.zhongshu.card.server.core.httpRequest.ApiRequestService;
import com.zhongshu.card.server.core.service.base.RedisService;
import com.zhongshu.card.server.core.service.base.SuperService;
import com.zhongshu.card.server.core.service.mqtt.mqttConfig.client.MQClient;
import com.zhongshu.card.server.core.service.mqtt.mqttConfig.constant.MQConstant;
import com.zhongshu.card.server.core.util.BeanUtils;
import com.zhongshu.card.client.utils.DateUtils;
import jakarta.jms.Message;
import jakarta.jms.TextMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.artemis.jms.client.ActiveMQBytesMessage;
import org.apache.activemq.artemis.jms.client.ActiveMQTopic;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author TRX
 * @date 2024/3/20
 */
@Slf4j
@Service
public class MqttServiceImpl extends SuperService {

    @Autowired
    UserCountDao userDao;

    @Autowired
    RedisService redisService;

    @Autowired
    MQClient mqClient;

    @Autowired
    ApiRequestService apiRequestService;

    @Autowired
    ArtemisMessageDao artemisMessageDao;

    @Autowired
    UserCountDao userCountDao;

    @Autowired
    MqttConfigDao mqttConfigDao;

    /**
     * 发送指令
     *
     * @param param
     * @return
     */
    public ResultContent sendMessage(SendMessageModel param) {
        String msg = "发送成功";
        try {
            String userId = param.getUserId();
            if (StringUtils.isEmpty(userId)) {
                userId = getCurrentUserId();
            }
            String id = UUID.randomUUID().toString();
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("id", id);
            jsonObject.addProperty("data", param.getMessage());
            jsonObject.addProperty("timeStr", DateUtils.paresTime(System.currentTimeMillis(), DateUtils.patternyyyySSS));
            jsonObject.addProperty("time", System.currentTimeMillis());
            jsonObject.addProperty("ttl", 10 * 1000);
            mqClient.sendObject(param.getTopic(), jsonObject.toString());

            ArtemisMessage artemisMessage = new ArtemisMessage();
            artemisMessage.setJsonObject(jsonObject);
            artemisMessage.setTopIc(param.getTopic());
            artemisMessage.setArtemisType(ArtemisType.Send);
            artemisMessage.setMessageId(id);
            artemisMessage.setTimeStr(DateUtils.paresTime(System.currentTimeMillis(),
                    DateUtils.patternyyyySSS));
            artemisMessage.setUserId(param.getUserId());
            if (StringUtils.isNotEmpty(userId)) {
                UserAccount userAccount = userCountDao.findTopByUserId(userId);
                if (ObjectUtils.isNotEmpty(userAccount)) {
                    artemisMessage.setUserName(userAccount.getName());
                }
            }
            artemisMessageDao.save(artemisMessage);
            log.info("mqtt msg 发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            msg = "发送失败： " + e.getMessage();
        }

//        str = str.replaceAll("\\t", "");
//        str = str.replaceAll("\\n", "");
        // 访问物联网平台
//        APIResponseModel resultContent = apiRequestService.sendIotCenterAPI(
//                IotCenterAPIConfig.sendMessage, param);
//        if (resultContent.isSuccess()) {
//
//        }
//        log.info("是否成功： {} {}", resultContent.isSuccess(), resultContent.getContent());
        return ResultContent.buildSuccess(msg);
    }

    //    @JmsListener(destination = "#", containerFactory = MQConstant.TopicListenerContainerFactory)
    @JmsListener(destination = "v1/#", containerFactory = MQConstant.TopicListenerContainerFactory)
    @JmsListener(destination = "v1.#", containerFactory = MQConstant.TopicListenerContainerFactory)
    public void receiveMessage(Message message) {
        // 处理接收到的消息
        try {
            ActiveMQTopic activeMQTopic = (ActiveMQTopic) message.getJMSDestination();
            String topicName = activeMQTopic.getTopicName();
            if (topicName.equals("activemq.notifications")) {
                return;
            }
            log.info("receiveMessage {} 消息监听clientId: {}", message.getJMSMessageID(), message.getStringProperty("__AMQ_CID"));
            log.info("Topic: {}", topicName);

            if (message instanceof ActiveMQBytesMessage) {
                ActiveMQBytesMessage activeMQBytesMessage = (ActiveMQBytesMessage) message;

                byte[] messageBody = new byte[(int) activeMQBytesMessage.getBodyLength()];
                // 读取消息内容到字节数组
                activeMQBytesMessage.readBytes(messageBody);
                String msg = new String(messageBody);
                JSONObject json = JSONUtil.parseObj(msg);
                log.info("消息内容：{}", json.get("msg"));
            }
            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                log.info("textMessage: {}", textMessage.getText());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到平台的MQTT连接配置
     *
     * @return
     */
    public ResultContent<List<MqttConfigModel>> getMqttConfig() {
        List<MqttConfig> list = mqttConfigDao.findAll(Sort.by(Sort.Order.asc("sort"),
                Sort.Order.asc("createTime")));
        List<MqttConfigModel> models = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(list)) {
            models = list.stream().map(this::toModel).collect(Collectors.toList());
        }
        return ResultContent.buildSuccess(models);
    }

    public MqttConfigModel toModel(MqttConfig entity) {
        MqttConfigModel model = null;
        if (entity != null) {
            model = new MqttConfigModel();
            BeanUtils.copyProperties(entity, model);
        }
        return model;
    }
}
