package jnpf.attendance.event;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import jnpf.attendance.service.AttendanceGroupService;
import jnpf.constants.MessageTopicConstants;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.message.enums.permission.v2.OperationTypeMessageEnums;
import jnpf.message.model.permission.v2.OrganizeUpdateMessageDTO;
import jnpf.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 组织变更消费者
 */
@Component
@RocketMQMessageListener(
        topic = MessageTopicConstants.PERMISSION_TOPIC,
        consumerGroup = MessageTopicConstants.JNPF_GROUP,
        selectorExpression = MessageTopicConstants.TAG_ORGANIZE,
        replyTimeout = 600000,
        maxReconsumeTimes = 3,
        nameServer = "${spring.cloud.stream.rocketmq.binder.name-server}"
)
@Slf4j
public class OrganizeConsumerMQListener implements RocketMQListener<String> {
    @Autowired
    private AttendanceGroupService attendanceGroupService;

    @Override
    public void onMessage(String message) {
        if (StringUtil.isEmpty(message)) {
            return;
        }
        log.error("接受组织变更信息{}", message);
        try {
            List<OrganizeUpdateMessageDTO> messageList = JSON.parseArray(message, OrganizeUpdateMessageDTO.class);
            if (CollUtil.isEmpty(messageList) || StringUtil.isEmpty(messageList.get(0).getId())) {
                return;
            }
            TenantDataSourceUtil.switchTenant(messageList.get(0).getTenantId());
            List<OrganizeUpdateMessageDTO> collect = messageList.stream().filter(vo -> Objects.equals(vo.getOperationTypeEnum(), OperationTypeMessageEnums.ADD) || Objects.equals(vo.getOperationTypeEnum(), OperationTypeMessageEnums.UPDATE)).collect(Collectors.toList());
            attendanceGroupService.batchSaveGroupByOrgIds(collect.get(0).getTenantId(), collect.stream().map(OrganizeUpdateMessageDTO::getId).collect(Collectors.toList()));
        } catch (Exception e) {
            log.error("消息解析异常: message={}", message, e);
        }

    }

}
