package com.yida.data.attendance.configure;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yida.data.attendance.dto.DealRecordDTO;
import com.yida.data.attendance.service.EduAttendanceRecordService;
import com.yida.data.common.core.entity.ReceiveMsg;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.user.EduStaff;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.common.core.enums.MsgChannel;
import com.yida.data.user.feign.RemoteStaffService;
import com.yida.data.user.feign.RemoteStudentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.JmsListener;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

@RequiredArgsConstructor
@Slf4j
@Configuration
public class ActiveMqConfigure {

    private final EduAttendanceRecordService eduAttendanceRecordService;
    private final RemoteStaffService remoteStaffService;
    private final RemoteStudentService remoteStudentService;
    private final RedisService redisService;

    private static Snowflake snowflake;

    static {
        snowflake = new Snowflake(1L, 1L);
    }

    @JmsListener(destination = "mq.bfms.client.msg.topic")
    public void consumeAttendance(String text) {
        try {
            // 保存接收消息到es
            ReceiveMsg receiveMsg = new ReceiveMsg();
            receiveMsg.setTopic("mq.bfms.client.msg.topic");
            receiveMsg.setMsg(text);
            receiveMsg.setId(snowflake.nextId());
            receiveMsg.setChannel(MsgChannel.ACTIVE.getValue());
            receiveMsg.setCreateDate(LocalDateTime.now());
            redisService.lSet(CachePrefixConstant.RECEIVE_MSG, receiveMsg);
            // 处理业务
            JSONObject json = JSONUtil.parseObj(text);
            String method = json.getStr("method");
            if ("bfms.notifyFaceInfo".equals(method)) {
                JSONObject data = json.getJSONObject("info");
                JSONArray jsonArray = data.getJSONArray("similarFaces");
                if (Objects.isNull(jsonArray)) {
                    return;
                }
                JSONObject personData = (JSONObject) jsonArray.get(0);
                String personId = personData.getStr("personId");
                Integer personType = personData.getInt("personTypeId");
                DealRecordDTO dto = new DealRecordDTO();
                String pictureUrl = data.getStr("pictureUrl");
                String[] pictureUrls = pictureUrl.split("\\|");
                if (pictureUrls.length < 2) {
                    // 图片未上传  不处理该数据
                    return;
                }
                dto.setPicUrl(pictureUrls[1]);
                dto.setDate(LocalDateTimeUtil.of(data.getLong("beginTime") * 1000)
                        .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                dto.setSn(data.getStr("channelId"));
                dto.setUserFlag(personId);
                Object userId = redisService.hget(CachePrefixConstant.USER_DAHUA_USER, personId);
                // 查询用户
                if (personType == 2) {
                    if (userId == null) {
                        EduStaff staff = remoteStaffService.getStaffByDahuaNoPermission(personId).getData();
                        if (staff != null) {
                            dto.setUserId(staff.getId());
                            redisService.hset(CachePrefixConstant.USER_DAHUA_USER, personId, dto.getUserId());
                        }
                    } else {
                        dto.setUserId(Long.valueOf(userId.toString()));
                    }
                    dto.setUserType(1);
                } else if (personType == 1) {
                    if (userId == null) {
                        EduStudent student = remoteStudentService.getStudentByDahuaNoPermission(personId).getData();
                        if (student != null) {
                            dto.setUserId(student.getId());
                            redisService.hset(CachePrefixConstant.USER_DAHUA_USER, personId, dto.getUserId());
                        }
                    } else {
                        dto.setUserId(Long.valueOf(userId.toString()));
                    }
                    dto.setUserType(0);
                }
                if (dto.getUserId() != null) {
                    eduAttendanceRecordService.receiveRecord(dto);
                }
            }
        } catch (Exception e) {
            log.error("处理大华人脸推送错误,接收消息:[{}]", text, e);
        }
    }
}
