package com.ruoyi.dj.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.dj.mqtt.client.DJICloudMQTTClient;
import com.ruoyi.dj.mqtt.common.CommonFieldsVo;
import com.ruoyi.dj.mqtt.dto.PropertySetDto;
import com.ruoyi.dj.mqtt.utils.PayloadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;

/**
 * @auther 周志雄
 * @date 2024/9/10 10:44
 */
@Slf4j
@Api(tags = "属性相关")
@RestController
@RequestMapping("/property")
public class PropertyController {
    @Resource
    private DJICloudMQTTClient djiCloudMQTTClient;

    private static final String PROPERTY_TOPIC = "thing/product/?/property/set";

    /**
     * 属性设置
     *
     * @param propertySetDto
     * @return
     */
    @ApiOperation("属性设置")
    @PostMapping("/set")
    public AjaxResult set(@RequestBody PropertySetDto propertySetDto) {
        String gateway = propertySetDto.getGateway();
        String topic = PROPERTY_TOPIC.replace("?", propertySetDto.getGateway());
        CommonFieldsVo commonFieldVo = CommonFieldsVo.createCommonFieldVo(null, propertySetDto.getGateway());
        String payload = PayloadUtil.generatePayload(commonFieldVo, propertySetDto.getParams());
        log.info("设置属性payload:{}", payload);
        // 发送消息之后直接成功、不需要等待回复
        CompletableFuture.runAsync(() -> {
            djiCloudMQTTClient.publishMessage(topic, payload, commonFieldVo);
        });
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return AjaxResult.success("操作成功");
    }
}
