package com.multictrl.modules.business.handler;

import cn.hutool.json.JSONObject;
import com.multictrl.common.constant.BusinessConstant;
import com.multictrl.common.utils.JsonUtils;
import com.multictrl.modules.business.dao.ZhimouCallbackDao;
import com.multictrl.modules.business.entity.ZhimouCallbackEntity;
import com.multictrl.modules.business.service.DJIBaseService;
import com.multictrl.modules.business.service.MqttPushService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 智眸回调处理
 *
 * @author Sdy
 * @since 1.0.0 2026/6/11
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ZhiMouCallbackHandler implements MessageHandler {
    private final ZhimouCallbackDao zhimouCallbackDao;
    private final DJIBaseService djiBaseService;
    private final MqttPushService mqttPushService;

    @Override
    public void handleMessage(String topic, String payload, String gateway) {
        log.debug("zhiMouCallback --> topic: {}, payload: {}", topic, payload);
        JSONObject data = JsonUtils.parseObject(payload, JSONObject.class);
        if (data != null) {
            String event = data.getStr("event");
            if ("start".equals(event) || "stop".equals(event)) {
                ZhimouCallbackEntity entity = new ZhimouCallbackEntity();
                entity.setAppId(data.getStr("app_id"));
                entity.setBusinessId(data.getStr("business_id"));
                entity.setDevice(data.getStr("device"));
                entity.setEvent(event);
                entity.setTaskId(data.getStr("task_id"));
                entity.setTimestamp(data.getLong("timestamp"));
                zhimouCallbackDao.insert(entity);

                //推送给前端
                JSONObject message = djiBaseService.getPayload(BusinessConstant.ZHIMOU_AI_METHOD, data);
                mqttPushService.pushMessageByClient1(BusinessConstant.WEB_EVENT_TOPIC.formatted(gateway), message.toString());
            }
        }
    }
}
