package cn.pluss.platform.config;

import cn.pluss.platform.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.onsmqtt.model.v20200420.SendMessageRequest;
import com.aliyuncs.onsmqtt.model.v20200420.SendMessageResponse;
import com.aliyuncs.profile.DefaultProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

@Component
@DependsOn("mqttConfig")
public class MqttSendMessage {

    private Logger logger  = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MqttConfig mqttConfig;

    private DefaultProfile profile;

    private IAcsClient client;

    @PostConstruct
    public void init() {
        if(profile == null){
            profile = DefaultProfile.getProfile(mqttConfig.getRegionId(), mqttConfig.getKeyId(), mqttConfig.getKeySecret());
        }
        if(client == null){
            client = new DefaultAcsClient(profile);
        }
    }

    public Map<String,String> sendMqttMessage(String deviceNo, JSONObject payload){
        logger.info("==============>推送Mqtt消息开始，推送设备编号:{},推送消息内容:{}<===============",deviceNo,payload);
        if(StringUtil.isEmpty(deviceNo)){
            logger.info("==============>推送Mqtt消息失败，推送设备编号为空!<=================");
            return null;
        }
        if(StringUtil.isEmpty(payload)){
            logger.info("==============>推送Mqtt消息失败，推送消息内容为空!<=================");
            return null;
        }
        SendMessageRequest request = new SendMessageRequest();
        request.setRegionId(mqttConfig.getRegionId());
        request.setInstanceId(mqttConfig.getInstanceId());
        request.setPayload(payload.toJSONString());
        String sendTopic = mqttConfig.getTopic() + "/order/" + mqttConfig.getGroupId() + "@@@" + deviceNo;
        logger.info("==============>推送Mqtt消息topic参数:{}<=================",sendTopic);
        request.setMqttTopic(sendTopic);
        try {
            SendMessageResponse response = client.getAcsResponse(request);
            if(response != null){
                return JSONObject.parseObject(JSON.toJSONString(response),Map.class);
            }
        } catch (ClientException e) {
            logger.info("==============>推送Mqtt消息失败，失败原因:{}<=================",e.getErrMsg());
            return null;
        }
        return null;
    }

}
