package com.multictrl.modules.business.handler;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.multictrl.common.constant.BusinessConstant;
import com.multictrl.common.utils.JsonUtils;
import com.multictrl.modules.business.dao.DeviceDicDao;
import com.multictrl.modules.business.dao.DockDeviceDao;
import com.multictrl.modules.business.entity.DeviceDicEntity;
import com.multictrl.modules.business.entity.DockDeviceEntity;
import com.multictrl.modules.business.service.MqttPushService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * status 设备拓扑更新消息处理器
 *
 * @author Sdy
 * @since 1.0.0 2026/4/23
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class StatusHandler implements MessageHandler {
    private final MqttPushService mqttPushService;
    private final DockDeviceDao dockDeviceDao;
    private final DeviceDicDao deviceDicDao;

    @Override
    public void handleMessage(String topic, String payload, String gateway) {
        log.debug("status --> topic: {}, payload: {}", topic, payload);
        JSONObject message = JsonUtils.parseObject(payload, JSONObject.class);
        if (message != null) {
            String method = message.getStr(BusinessConstant.METHOD);
            JSONObject data = message.getJSONObject(BusinessConstant.DATA);
            if (BusinessConstant.UPDATE_TOPO.equals(method)) {//设备拓扑更新
                log.debug("status --> 设备拓扑更新{}", data.toString());
                //更新设备信息
                if (!data.isEmpty()) {
                    //机库
                    DockDeviceEntity dockDevice = dockDeviceDao.selectOne(new QueryWrapper<DockDeviceEntity>()
                            .eq("sn", gateway).isNull("parent_sn"));
                    if (dockDevice != null) {
                        updateDeviceInfo(data, dockDevice);
                    }
                    //设备
                    JSONArray subDevices = data.getJSONArray("sub_devices");
                    if (subDevices != null && !subDevices.isEmpty()) {
                        for (Object device : subDevices) {
                            JSONObject deviceJson = (JSONObject) device;
                            String sn = deviceJson.getStr("sn");
                            DockDeviceEntity uavDevice = dockDeviceDao.selectOne(new QueryWrapper<DockDeviceEntity>()
                                    .eq("sn", sn).eq("parent_sn", gateway));
                            if (uavDevice != null) {
                                updateDeviceInfo(deviceJson, uavDevice);
                            }
                        }
                    }
                } else {
                    data = new JSONObject();
                }
                data.clear();
                data.set("result", 0);
                message.remove(BusinessConstant.NEED_REPLY);
                mqttPushService.pushMessageByClient1(topic + BusinessConstant._REPLY, message.toString());
                log.debug("status--> 设备拓扑更新发送成功");
            }
        } else {
            log.debug("status --> payload解析失败，解析后为null");
        }
    }

    //更新设备信息
    private void updateDeviceInfo(JSONObject data, DockDeviceEntity device) {
        String domain = data.getStr("domain");
        Integer type = data.getInt("type");
        Integer subType = data.getInt("sub_type");
        device.setDeviceModelKey(domain + "-" + type + "-" + subType);
        device.setDomain(Integer.parseInt(domain));
        device.setDeviceType(type);
        device.setSubType(subType);
        device.setDeviceSecret(data.getStr("device_secret"));
        device.setNonce(data.getStr("nonce"));
        device.setThingVersion(data.getStr("thing_version"));
        device.setUpdateDate(new Date());
        DeviceDicEntity deviceDicEntity = deviceDicDao.selectOne(new QueryWrapper<DeviceDicEntity>()
                .eq("domain", device.getDomain())
                .eq("device_type", device.getDeviceType())
                .eq("sub_type", device.getSubType()));
        device.setDeviceName(deviceDicEntity != null ? deviceDicEntity.getDeviceName() : "unknown");
        dockDeviceDao.updateById(device);
    }
}
