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.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.mqtt.MqttSubscribe;
import com.xjrsoft.common.utils.LocalDateTimeUtil;
import com.xjrsoft.module.personnel.entity.FaceIdentifyRecords;
import com.xjrsoft.module.personnel.service.IFaceIdentifyRecordsService;
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/identify")
@Slf4j
public class FaceIdentify implements IMqttMessageListener {
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {

        try {
            IFaceIdentifyRecordsService faceIdentifyRecordsService = SpringUtil.getBean(IFaceIdentifyRecordsService.class);

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

            System.out.println("reply payload: " + message.toDebugString());

            FaceIdentifyRecords params = new FaceIdentifyRecords();
            params.setFaceIdentifySyncId(jsonObject.getInt("id"));
            params.setMacAddr(jsonObject.getStr("Mac_addr"));
            params.setVerifyTime(LocalDateTimeUtil.parseDate(jsonObject.getStr("time")));
            params.setDeviceName(jsonObject.getStr("devicename"));
            params.setLocation(jsonObject.getStr("location"));
            params.setInoutDirection(jsonObject.getInt("inout"));
            params.setFaceCode(jsonObject.getStr("employee_number"));
            params.setName(jsonObject.getStr("name"));
            params.setTemperature(jsonObject.getStr("temperature"));
            params.setResultStatus(jsonObject.getInt("resultStatus"));
            params.setIdentifyType(jsonObject.getInt("IdentifyType"));
            params.setFaceBase64("data:image/jpeg;base64," + jsonObject.getStr("face_base64"));

            long count = faceIdentifyRecordsService.count(Wrappers.<FaceIdentifyRecords>lambdaQuery().eq(FaceIdentifyRecords::getFaceIdentifySyncId, params.getFaceIdentifySyncId()));
            if (count == 0) {
                faceIdentifyRecordsService.save(params);
            }
        } catch (Exception e) {
            log.error(this.getClass().getName(), e.getMessage());
        }
    }
}
