package com.xjrsoft.module.mqtt.car.service;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xjrsoft.common.mqtt.EmqClient;
import com.xjrsoft.common.mqtt.MqttSubscribe;
import com.xjrsoft.module.personnel.entity.CarManagement;
import com.xjrsoft.module.personnel.service.ICarManagementService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.mqttv5.client.IMqttMessageListener;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.springframework.stereotype.Component;

/**
 * 修改车辆回调
 */
@Component
@MqttSubscribe(topic = "/car/identify/update/reply")
@Slf4j
public class CarIdentifyUpdateReply implements IMqttMessageListener {
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        try {
            EmqClient emqClient = SpringUtil.getBean(EmqClient.class);
            ICarManagementService carManagementService = SpringUtil.getBean(ICarManagementService.class);

            // 获取请求参数
            String params = emqClient.getRequestParams(new String(message.getProperties().getCorrelationData()));
            JSONObject jsonParams = JSONUtil.parseObj(params);

            // 获取回复数据
            JSONObject jsonObject = JSONUtil.parseObj(message.toString());

            // 根据车牌查询车辆信息
            LambdaQueryWrapper<CarManagement> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CarManagement::getCarNo, jsonParams.getStr("carNo"));
            CarManagement carManagement = carManagementService.getOne(queryWrapper);

            if (carManagement == null) {
                return;
            }

            CarManagement updateParams = new CarManagement();
            updateParams.setId(carManagement.getId());

            // 判断回复结果是否成功
            int code = jsonObject.getInt("code");
            if (code == 0) {
                updateParams.setSyncStatus(2);
            } else {
                updateParams.setSyncStatus(3);
            }
            carManagementService.updateById(updateParams);
        } catch (Exception e) {
            log.error(this.getClass().getName(), e.getMessage());
        }
    }
}
