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

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xjrsoft.common.mqtt.EmqClient;
import com.xjrsoft.common.mqtt.MqttSubscribe;
import com.xjrsoft.module.personnel.entity.FaceManagement;
import com.xjrsoft.module.personnel.service.IFaceManagementService;
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 = "/face/device/personnel/image/verify/reply")
@Slf4j
public class FaceImageVerify implements IMqttMessageListener {
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {

        try {
            EmqClient emqClient = SpringUtil.getBean(EmqClient.class);
            IFaceManagementService faceManagementService = SpringUtil.getBean(IFaceManagementService.class);

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

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

            FaceManagement updateParams = new FaceManagement();
            updateParams.setId(id);

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