package jnpf.attendance.event;

import com.alibaba.fastjson.JSON;
import jnpf.attendance.service.AttendanceUserService;
import jnpf.constants.MessageTopicConstants;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.message.model.permission.PermissionRelationOrganizeUserListDTO;
import jnpf.model.attendance.model.TurnoverConsumerModel;
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;

/**
 * 终止入职信息
 */
@Component
@RocketMQMessageListener(
        topic = MessageTopicConstants.PERSONNEL_SECONDMENT_FAIL_TOPIC,
        consumerGroup = MessageTopicConstants.ONBOARDING_FAIL_GROUP,
        replyTimeout = 600000,
        maxReconsumeTimes = 3,
        nameServer = "${spring.cloud.stream.rocketmq.binder.name-server}"
)
@Slf4j
public class OnboardingFailConsumerMQListener implements RocketMQListener<String> {
    @Autowired
    private AttendanceUserService attendanceUserService;

    @Override
    public void onMessage(String message) {
        if (StringUtil.isEmpty(message)) {
            return;
        }
        log.error("接受终止入职信息{}", message);
        try {
            TurnoverConsumerModel messageList = JSON.parseObject(message, TurnoverConsumerModel.class);
            if (Objects.isNull(messageList)) {
                return;
            }
            TenantDataSourceUtil.switchTenant(messageList.getTenantId());
            PermissionRelationOrganizeUserListDTO permissionRelationOrganizeUserListDTO = new PermissionRelationOrganizeUserListDTO();
            permissionRelationOrganizeUserListDTO.setOldOrganizeId(messageList.getCurrOrgId());
            permissionRelationOrganizeUserListDTO.setUserId(messageList.getUserId());
            //删
            attendanceUserService.removeUsers(List.of(permissionRelationOrganizeUserListDTO),false);
        } catch (Exception e) {
            log.error("消息解析异常: message={}", message, e);
        }

    }

}
