package jnpf.qualifications.consummer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.base.UserInfo;
import jnpf.config.ConfigValueUtil;
import jnpf.cultivate.mapper.FtbCultivatePromotionMemberNewMapper;
import jnpf.cultivate.service.FtbCultivatePositionService;
import jnpf.cultivate.utils.CultivateLearnUtils;
import jnpf.cultivate.v2.service.V2CultivatePositionService;
import jnpf.cultivate.v2.service.V2CultivatePromotionService;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.entity.qualifications.Qualifications;
import jnpf.exception.HandleException;
import jnpf.exception.LoginException;
import jnpf.message.enums.permission.v2.OperationTypeMessageEnums;
import jnpf.message.model.permission.PermissionRelationUserPositionListDTO;
import jnpf.message.model.permission.v2.GradeRelationPositionMessageDTO;
import jnpf.message.model.permission.v2.GradeUpdateMessageDTO;
import jnpf.message.model.permission.v2.PositionUpdateMessageDTO;
import jnpf.model.cultivate.po.position.FtbCultivatePosition;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotionPostNew;
import jnpf.qualifications.service.QualificationsService;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import jnpf.util.data.DataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.context.annotation.Lazy;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.PreDestroy;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@Slf4j
@Component
@EnableBinding(PositionGradeConsumerSource.class)
public class PositionGradeConsumer {

    @Value("${ftb.consumer.group.start.date:2025-09-24}")
    private String startDate;
    @Autowired
    @Lazy
    private ConfigValueUtil configValueUtil;

    @Autowired
    @Lazy
    private QualificationsService qualificationsService;

    @Autowired
    @Lazy
    private FtbCultivatePositionService ftbCultivatePositionService;

    @Autowired
    @Lazy
    private FtbCultivatePromotionMemberNewMapper ftbCultivatePromotionMemberNewMapper;


    private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);


    @Autowired
    @Lazy
    private V2CultivatePromotionService v2CultivatePromotionService;
    @Autowired
    @Lazy
    private V2CultivatePositionService v2CultivatePositionService;


    @Autowired
    @Lazy
    private CultivateLearnUtils cultivateLearnUtils;

    /**
     * 处理职级删除消息
     *
     * @param message 消息
     */
    @StreamListener(target = PositionGradeConsumerSource.INPUT, condition = "headers['ROCKET_TAGS'] == 'TAG_GRADE'")
    public void receiveDeleteGrade(Message<String> message) {
        // 获取消息体
        String payload = message.getPayload();
        // 获取 headers
        MessageHeaders headers = message.getHeaders();
        if (StringUtil.isEmpty(payload)) {
            return;
        }
        if (!checkTime(headers)) {
            return;
        }
        List<GradeUpdateMessageDTO> messageList = null;
        try {
            messageList = JSONUtil.toList(payload, GradeUpdateMessageDTO.class);
        } catch (Exception e) {
            log.error("message={}", payload);
            log.error("jnpf.consumer.PositionGradeConsumer.receiveDeleteGrade信息解析异常：", e);
            return;
        }

        if (CollectionUtil.isEmpty(messageList)) {
            return;
        }
        for (GradeUpdateMessageDTO messageDTO : messageList) {
            if (StringUtil.isEmpty(messageDTO.getId()) || messageDTO.getOperationTypeEnum() == null || !OperationTypeMessageEnums.DELETE.getCode().equals(messageDTO.getOperationTypeEnum().getCode())) {
                continue;
            }

            if (StringUtil.isEmpty(messageDTO.getTenantId())) {
                continue;
            }
            switchDb(messageDTO.getTenantId());
            List<Qualifications> qualifications = qualificationsService.selectByGradeId(messageDTO.getId());
            if (CollectionUtil.isEmpty(qualifications)) {
                continue;
            }
            for (Qualifications qualification : qualifications) {
                try {
                    qualificationsService.delete(qualification.getId());
                } catch (HandleException e) {
                    log.error("删除失败", e);
                }
            }
        }
    }

    /**
     * 岗位和职级解绑
     *
     * @param message 消息
     */
    @StreamListener(target = PositionGradeConsumerSource.INPUT, condition = "headers['ROCKET_TAGS'] == 'TAG_GRADE_RELATION_POSITION'")
    public void receiveUnbindPositionAndGrade(Message<String> message) {
        // 获取消息体
        String payload = message.getPayload();
        // 获取 headers
        MessageHeaders headers = message.getHeaders();
        if (StringUtil.isEmpty(payload)) {
            return;
        }
        if (!checkTime(headers)) {
            return;
        }
        List<GradeRelationPositionMessageDTO> messageList = null;
        try {
            messageList = JSONUtil.toList(payload, GradeRelationPositionMessageDTO.class);
        } catch (Exception e) {
            log.error("message={}", payload);
            log.error("jnpf.consumer.PositionGradeConsumer.receiveUnbindPositionAndGrade信息解析异常：", e);
            return;
        }

        if (CollectionUtil.isEmpty(messageList)) {
            return;
        }
        for (GradeRelationPositionMessageDTO messageDTO : messageList) {
            if (StringUtil.isEmpty(messageDTO.getId()) || StringUtil.isEmpty(messageDTO.getLinkId()) || messageDTO.getOperationTypeEnum() == null || !OperationTypeMessageEnums.DELETE.getCode().equals(messageDTO.getOperationTypeEnum().getCode())) {
                continue;
            }
            switchDb(messageDTO.getTenantId());
            String positionId = messageDTO.getLinkId();
            String gradeId = messageDTO.getId();

            List<Qualifications> qualifications = qualificationsService.selectByGradeIdAndPositionId(positionId, gradeId);
            if (CollectionUtil.isEmpty(qualifications)) {
                continue;
            }
            for (Qualifications qualification : qualifications) {
                try {
                    qualificationsService.delete(qualification.getId());
                } catch (HandleException e) {
                    log.error("删除失败", e);
                }
            }

        }
    }


    /**
     * 删除岗位
     *
     * @param message 消息
     */
    @StreamListener(target = PositionGradeConsumerSource.INPUT, condition = "headers['ROCKET_TAGS'] == 'TAG_POSITION'")
    public void receiveDeletePosition(Message<String> message) {
        // 获取消息体
        String payload = message.getPayload();
        // 获取 headers
        MessageHeaders headers = message.getHeaders();
        if (StringUtil.isEmpty(payload)) {
            return;
        }
        if (!checkTime(headers)) {
            return;
        }
        List<PositionUpdateMessageDTO> messageList = null;
        try {
            messageList = JSONUtil.toList(payload, PositionUpdateMessageDTO.class);
        } catch (Exception e) {
            log.error("message={}", payload);
            log.error("jnpf.consumer.PositionGradeConsumer.receiveDeletePosition信息解析异常：", e);
            return;
        }

        if (CollectionUtil.isEmpty(messageList)) {
            return;
        }
        for (PositionUpdateMessageDTO messageDTO : messageList) {
            if (StringUtil.isEmpty(messageDTO.getId()) || messageDTO.getOperationTypeEnum() == null || !OperationTypeMessageEnums.DELETE.getCode().equals(messageDTO.getOperationTypeEnum().getCode())) {
                continue;
            }
            if (StringUtil.isEmpty(messageDTO.getTenantId())) {
                continue;
            }
            switchDb(messageDTO.getTenantId());
            String positionId = messageDTO.getId();
            List<FtbCultivatePromotionPostNew> promotionPostNewList = ftbCultivatePromotionMemberNewMapper.queryRelationMap(positionId);
            if (CollUtil.isNotEmpty(promotionPostNewList)) {
                v2CultivatePromotionService.updatePromotionError(promotionPostNewList);
            }

            LambdaQueryWrapper<FtbCultivatePosition> positionLambdaQueryWrapper = Wrappers.lambdaQuery();
            positionLambdaQueryWrapper.eq(FtbCultivatePosition::getEnabledMark, 0);
            positionLambdaQueryWrapper.eq(FtbCultivatePosition::getPostId, positionId);
            List<FtbCultivatePosition> list = ftbCultivatePositionService.list(positionLambdaQueryWrapper);
            if (CollectionUtil.isEmpty(list)) {
                continue;
            }
            for (FtbCultivatePosition ftbCultivatePosition : list) {
                v2CultivatePositionService.delete(ftbCultivatePosition.id);
            }
        }
    }


    /**
     * 用户岗位信息变更
     *
     * @param message 消息
     */
    @StreamListener(target = PositionGradeConsumerSource.INPUT, condition = "headers['ROCKET_TAGS'] == 'TAG_USER_RELATION_POSITION'")
    public void receiveUserPositionChange(Message<String> message) {
        // 获取消息体
        String payload = message.getPayload();
        log.error("TAG_USER_RELATION_POSITION={}", payload);
        // 获取 headers
        MessageHeaders headers = message.getHeaders();
        if (StringUtil.isEmpty(payload)) {
            return;
        }
        if (!checkTime(headers)) {
            return;
        }
        List<PermissionRelationUserPositionListDTO> messageList = null;
        try {
            messageList = JSONUtil.toList(payload, PermissionRelationUserPositionListDTO.class);
        } catch (Exception e) {
            log.error("message={}", payload);
            log.error("jnpf.message.model.permission.PermissionRelationUserPositionListDTO信息解析异常：", e);
            return;
        }

        if (CollectionUtil.isEmpty(messageList)) {
            return;
        }
        for (PermissionRelationUserPositionListDTO messageDTO : messageList) {
            if (StringUtil.isEmpty(messageDTO.getUserId())) {
                continue;
            }
            if (StringUtil.isEmpty(messageDTO.getTenantId())) {
                continue;
            }
            switchDb(messageDTO.getTenantId());
            String userId = messageDTO.getUserId();
            String positionId = messageDTO.getPositionId();
            String oldPositionId = messageDTO.getOldPositionId();
            if (StringUtil.isEmpty(positionId)) {
                continue;
            }
            if (StringUtil.isNotEmpty(oldPositionId) && oldPositionId.equals(positionId)) {
                continue;
            }
            cultivateLearnUtils.addPromotionUser(List.of(userId), messageDTO.getTenantId());

        }
    }


    public void switchDb(String tenantId) {
        // 判断是否为多租户
        if (configValueUtil.isMultiTenancy()) {
            // 判断是不是从外面直接请求
            if (StringUtil.isNotEmpty(tenantId)) {
                //切换成租户库
                try {
                    TenantDataSourceUtil.switchTenant(tenantId);
                } catch (LoginException e) {
                    throw new RuntimeException("切换租户失败");
                }
            } else {
                UserInfo userInfo = UserProvider.getUser();
                Assert.notNull(userInfo.getUserId(), "缺少租户信息");
                DataSourceContextHolder.setDatasource(userInfo.getTenantId(), userInfo.getTenantDbConnectionString(), userInfo.isAssignDataSource());
            }
        }
    }

    @PreDestroy
    public void destroy() {
        if (scheduler != null && !scheduler.isShutdown()) {
            scheduler.shutdown();
        }
    }


    private boolean checkTime(MessageHeaders headers) {

        Long timestamp = headers.getTimestamp();
        if (timestamp == null) {
            return false;
        }
        // 将timestamp格式化为字符串
        String timestampStr = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date(timestamp));
        // 比较字符串大小
        return timestampStr.compareTo(startDate) >= 0;
    }


}
