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

import cn.hutool.core.date.DateUtil;
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.common.utils.ImageUtil;
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.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 验证成功图片下发
 */
@Component
@MqttSubscribe(topic = "/face/device/personnel/image/verify/success")
@Slf4j
public class FaceImageVerifySuccess 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);

            // 查询未同步数据
            LambdaQueryWrapper<FaceManagement> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FaceManagement::getVerifyStatus, 2);
            queryWrapper.eq(FaceManagement::getSyncStatus, 1);
            List<FaceManagement> faceManagementList = faceManagementService.list(queryWrapper);

            faceManagementList.forEach(f -> {
                // 推送数据客户端
                JSONObject jsonObject = JSONUtil.createObj()
                        .put("id", f.getId().toString())
                        .put("idno", f.getIdno())
                        .put("employee_number", f.getFaceCode())
                        .put("name", f.getName())
                        .put("sex", f.getSex())
                        .put("peoplestadate", DateUtil.format(f.getPeopleStartDate(), "yyyy-MM-dd HH:mm:ss"))
                        .put("peopleenddate", DateUtil.format(f.getPeopleEndDate(), "yyyy-MM-dd HH:mm:ss"))
                        .put("register_base64", ImageUtil.base64RemovePrefix(f.getRegisterBase64()));

                try {
                    emqClient.publish("/face/device/personnel/add", jsonObject);
                } catch (MqttException e) {
                    log.error("mqtt", "publish", "/face/device/personnel/add", e.getMessage());
                }
            });
        } catch (Exception e) {
            log.error(this.getClass().getName(), e.getMessage());
        }
    }
}
