package com.red.circle.other.app.listener;

import com.red.circle.common.business.core.enums.DataApprovalTypeEnum;
import com.red.circle.component.mq.MessageEventProcess;
import com.red.circle.component.mq.MessageEventProcessDescribe;
import com.red.circle.component.mq.config.RocketMqMessageListener;
import com.red.circle.component.mq.service.Action;
import com.red.circle.component.mq.service.ConsumerMessage;
import com.red.circle.component.mq.service.MessageListener;
import com.red.circle.external.inner.model.enums.message.OfficialNoticeTypeEnum;
import com.red.circle.mq.business.model.event.approval.ApprovalEvent;
import com.red.circle.mq.rocket.business.streams.ConsoleApprovalSink;
import com.red.circle.other.app.listener.strategy.FactoryForApprovalStrategy;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.rds.entity.approval.ApprovalUserViolationHistory;
import com.red.circle.other.infra.database.rds.service.approval.ApprovalUserViolationHistoryService;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import com.red.circle.tool.core.text.StringUtils;
import java.util.List;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author pengliang on 2020/4/12 11:30
 */
@Slf4j
@RocketMqMessageListener(groupId = ConsoleApprovalSink.INPUT, tag = ConsoleApprovalSink.TAG)
@RequiredArgsConstructor
public class ApprovalListener implements MessageListener {

  private final UserProfileGateway userProfileGateway;
  private final MessageEventProcess messageEventProcess;
  private final FactoryForApprovalStrategy factoryForApprovalStrategy;
  private final ApprovalUserViolationHistoryService approvalUserViolationHistoryService;

  @Override
  public Action consume(ConsumerMessage message) {
    return messageEventProcess.consume(
        MessageEventProcessDescribe.builder()
            .logTag("后台审核")
            .consumeMsgTimeoutMinute(60)
            .repeatConsumeMinute(1)
            .repeatConsumeTag("ConsoleApproval")
            .checkConsumeTag(ConsoleApprovalSink.TAG)
            .message(message)
            .build(),
        ApprovalEvent.class,
        eventBody -> {
          log.info("后台审核, 审核类型: {}, 审核内容: {}", eventBody.getApprovalType(), eventBody);
          // 审批处理
          factoryForApprovalStrategy.getStrategy(eventBody.getApprovalType()).doOperation(eventBody);

          // 类型为举报动态则不继续往下处理
          if (DataApprovalTypeEnum.checkDynamic(eventBody.getApprovalType())) {
            return;
          }

          // 清理用户缓存
          userProfileGateway.removeCacheAll(eventBody.waitApprovalUserIdsSet());

          if (eventBody.approvalNotPass()) {
            // 记录审批历史
            saveApprovalUserViolationHistory(eventBody);
            // 违规通知
            sendViolationNotice(eventBody);
          }
        }
    );

  }

  private void sendViolationNotice(ApprovalEvent approvalParam) {
//    OfficialNoticeTypeEnum officialNoticeTypeEnum = approvalTypeToOfficialNoticeType(
//        approvalParam);
//    if (Objects.nonNull(officialNoticeTypeEnum)) {
//      officialNoticeClient.send(approvalParam.getWaitApprovalUserIds(),
//          officialNoticeTypeEnum);
//    }
  }

  public OfficialNoticeTypeEnum approvalTypeToOfficialNoticeType(ApprovalEvent approvalParam) {
//        if (Objects.equals(approvalType, DataApprovalTypeEnum.NICKNAME)) {
//            return OfficialNoticeTypeEnum.NICKNAME_CHECK_FAIL;
//        }
//
//        if (Objects.equals(approvalType, DataApprovalTypeEnum.AVATAR)) {
//            return OfficialNoticeTypeEnum.AVATAR_VIOLATION;
//        }
//
//        if (Objects.equals(approvalType, DataApprovalTypeEnum.PHOTO_WALL)) {
//            return OfficialNoticeTypeEnum.PHOTO_WALL_VIOLATION;
//        }
//
//        if (Objects.equals(approvalType, DataApprovalTypeEnum.LIVE)) {
//            return OfficialNoticeTypeEnum.LIVE_CHECK_FAIL;
//        }
//
//        if (Objects.equals(approvalType, DataApprovalTypeEnum.SHORT_VIDEO)) {
//            return OfficialNoticeTypeEnum.SHORT_VIDEO_VIOLATION;
//        }
    return null;
  }

  private void saveApprovalUserViolationHistory(ApprovalEvent approvalParam) {
    List<ApprovalUserViolationHistory> approvalUserViolationHistories = approvalParam
        .getWaitApprovalUser().stream()
        .map(approval -> {
          var history = new ApprovalUserViolationHistory()
              .setId(IdWorkerUtils.getId())
              .setUserId(approval.getUserId())
              .setOriginType(getType(approvalParam))
              .setViolationType(approvalParam.getApprovalType().name())
              .setLabelNames(StringUtils.isBlankOrElse(approval.getTags(), "-"))
              .setApprovalResult(Objects.toString(approvalParam.getApprovalStatus()))
              .setContentId(approval.getContentId())
              .setContent(approval.getContent())
              .setDescription("-");
          history.setCreateUser(approvalParam.getOpsUserId());
          history.setUpdateUser(approvalParam.getOpsUserId());
          history.setCreateTime(TimestampUtils.now());
          history.setUpdateTime(TimestampUtils.now());
          return history;
        }).toList();
    approvalUserViolationHistoryService.saveBatch(approvalUserViolationHistories);
  }

  private static int getType(ApprovalEvent approvalParam) {
    return Objects.equals(approvalParam.getOpUserType().getType(), 0) ? 1 : 0;
  }

}
