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.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.attendance.dto.AddAttendanceRecordDTO;
import com.yida.data.attendance.service.AttendanceRecordService;
import com.yida.data.attendance.service.EduAttendanceDeviceService;
import com.yida.data.attendance.service.ErrorRecordMsgService;
import com.yida.data.common.core.entity.ErrorRecordMsg;
import com.yida.data.common.core.entity.ReceiveMsg;
import com.yida.data.common.core.entity.attendance.EduAttendanceDevice;
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.common.core.enums.RecordTypeEnum;
import com.yida.data.user.feign.RemoteStaffService;
import com.yida.data.user.feign.RemoteStudentService;

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

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.JmsListener;

@RequiredArgsConstructor
@Slf4j
@Configuration
public class ActiveMqConfigure {

    private final AttendanceRecordService attendanceRecordService;
    private final RemoteStaffService remoteStaffService;
    private final RemoteStudentService remoteStudentService;
    private final RedisService redisService;
    private final ErrorRecordMsgService errorRecordMsgService;
    private final EduAttendanceDeviceService eduAttendanceDeviceService;

    public static final String TOPIC = "mq.bfms.client.msg.topic";

    private static final Snowflake SNOWFLAKE;

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

    @JmsListener(destination = "mq.bfms.client.msg.topic")
    public void consumeAttendance(String text) {
        AddAttendanceRecordDTO dto = new AddAttendanceRecordDTO();
        Long schoolId = null;
        try {
            // 保存接收消息到es
            ReceiveMsg receiveMsg = new ReceiveMsg();
            receiveMsg.setTopic(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");

                // 设备号
                String sn = data.getStr("channelId");
                // 查询设备信息
                EduAttendanceDevice attendanceDevice = eduAttendanceDeviceService.getOne(Wrappers.lambdaQuery(new EduAttendanceDevice())
                        .eq(EduAttendanceDevice::getSn, sn));
                if (Objects.isNull(attendanceDevice)) {
                    log.error("设备信息不存在: {}", sn);
                    return;
                }
                schoolId = attendanceDevice.getSchoolId();
                dto.setSchoolId(attendanceDevice.getSchoolId());
                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.setCreateTime(LocalDateTimeUtil.of(data.getLong("beginTime") * 1000));
                dto.setDeviceSn(sn);
                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(0);
                } 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(1);
                }
                dto.setMsgChannel(MsgChannel.ACTIVE);
                if (dto.getUserId() != null) {
                    log.info("大华人脸识别信息:[{}]", dto);
                    attendanceRecordService.addRecord(dto);
                }
            }
        } catch (Exception e) {
            log.error("处理大华人脸推送错误,接收消息:[{}]", text, e);
            errorRecordMsgService.saveMsg(ErrorRecordMsg.builder()
//                    .id(SNOWFLAKE.nextId())
                    .createDate(LocalDateTime.now())
                    .schoolId(schoolId)
                    .msg(JSONUtil.toJsonStr(dto))
                    .topic(TOPIC)
                    .channel(MsgChannel.ACTIVE.getValue())
                    .recordType(RecordTypeEnum.PANEL_MACHINE.getType())
                    .build()
            );
        }
    }
}
