package com.red.circle.other.app.command.dynamic;

import com.red.circle.common.business.core.ReplaceString;
import com.red.circle.common.business.core.SensitiveWordFilter;
import com.red.circle.common.business.enums.AccountStatusEnum;
import com.red.circle.common.business.enums.DynamicMessageEnum;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.app.common.room.DynamicCommon;
import com.red.circle.other.app.dto.cmd.dynamic.DynamicCommentCmd;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.model.user.UserConsumptionLevel;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.infra.common.user.UserAccountCommon;
import com.red.circle.other.infra.database.cache.service.other.DynamicCacheService;
import com.red.circle.other.infra.database.mongo.service.dynamic.DynamicPopularService;
import com.red.circle.other.infra.database.rds.entity.dynamic.DynamicComment;
import com.red.circle.other.infra.database.rds.entity.dynamic.DynamicContent;
import com.red.circle.other.infra.database.rds.entity.dynamic.DynamicMessage;
import com.red.circle.other.infra.database.rds.service.dynamic.DynamicCommentService;
import com.red.circle.other.infra.database.rds.service.dynamic.DynamicContentService;
import com.red.circle.other.infra.database.rds.service.dynamic.DynamicMessageService;
import com.red.circle.other.inner.asserts.DynamicErrorCode;
import com.red.circle.other.inner.model.cmd.user.account.PunishmentAccountCmd;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.num.NumUtils;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 动态-评论.
 * </p>
 *
 * @author pengshigang
 * @since 2022-04-12
 */
@Component
@RequiredArgsConstructor
public class DynamicCommentCmdExe {

  private final DynamicCommon dynamicCommon;
  private final UserProfileGateway userProfileGateway;
  private final DynamicCacheService dynamicCacheService;
  private final DynamicContentService dynamicContentService;
  private final DynamicMessageService dynamicMessageService;
  private final DynamicCommentService dynamicCommentService;
  private final DynamicPopularService dynamicPopularService;
  private final UserAccountCommon userAccountCommon;

  public String execute(DynamicCommentCmd cmd) {
    ResponseAssert.isTrue(DynamicErrorCode.CURRENT_LEVEL_IS_TOO_LOW, commentLimit(cmd));

    DynamicContent dynamicContent = checkParams(cmd);

    //保存评论
    Long commentId = IdWorkerUtils.getId();
    saveComment(cmd, commentId);

    String commentQuantity = incrCommentQuantity(cmd);

    //评论自己创建的动态或者自己回复自己不发送消息
    if (isOwnDynamic(cmd, dynamicContent)) {
      return commentQuantity;
    }

    dynamicPopularService.updateScore(dynamicContent.getId(), dynamicCacheService.getCommentScore(),
        cmd.getReqSysOrigin().getOrigin(), dynamicContent.getRegion());

    //评论不属于自己的动态，发送消息
    if (Objects.isNull(cmd.getToUserId())) {
      cmd.setToUserId(dynamicContent.getCreateUser());
      saveDynamicMessage(cmd, DynamicMessageEnum.COMMENT_DYNAMIC);
      dynamicCommon.sendMsg(cmd.getToUserId());
      return commentQuantity;
    }

    //发送消息给动态被回复人
    saveDynamicMessage(cmd, DynamicMessageEnum.REPLY_COMMENT);
    dynamicCommon.sendMsg(cmd.getToUserId());
    return commentQuantity;
  }

  private boolean commentLimit(DynamicCommentCmd cmd) {

    UserConsumptionLevel userLevel =
        userProfileGateway.getUserConsumptionLevel(
            cmd.requireReqSysOriginEnum(),
            cmd.requiredReqUserId()
        );

    if (Objects.isNull(userLevel)) {
      return false;
    }

    if (Objects.isNull(userLevel.getWealthLevel()) && Objects.isNull(userLevel.getCharmLevel())) {
      return false;
    }

    Long level = dynamicCacheService.getSendLevelLimit();
    if (Objects.isNull(level)) {
      return false;
    }

    if (Objects.nonNull(userLevel.getWealthLevel()) && userLevel.getWealthLevel() < level) {
      return false;
    }

    if (Objects.nonNull(userLevel.getCharmLevel()) && userLevel.getCharmLevel() < level) {
      return false;
    }

    return true;
  }

  private DynamicContent checkParams(DynamicCommentCmd cmd) {

    ResponseAssert.isTrue(DynamicErrorCode.CONTENT_IS_NULL, isNotBlank(cmd));
    DynamicContent dynamicContent = dynamicContentService.getById(cmd.getId());
    ResponseAssert.notNull(DynamicErrorCode.CONTENT_IS_NULL, dynamicContent);
    ResponseAssert.isFalse(DynamicErrorCode.CONTENT_DELETE, dynamicContent.getDel());
    if (SensitiveWordFilter.checkSensitiveWord(cmd.getContent())){
      // 封禁账号及设备
//      userAccountCommon.punishmentPro(new PunishmentAccountCmd()
//          .setBeOptUserId(cmd.getReqUserId())
//          .setOptUserId(cmd.requiredReqUserId())
//          .setStatus(AccountStatusEnum.ARCHIVE)
//          .setDescription("【动态涉及敏感词】封号+设备-" + cmd.getContent())
//      );
//
//      UserProfile userProfile = new UserProfile();
//      userProfile.setId(cmd.getReqUserId());
//      userProfile.setCheckStatus(AccountStatusEnum.ARCHIVE.name());
//      userProfileGateway.updateSelectiveById(userProfile);
      ResponseAssert.isTrue(DynamicErrorCode.SENSITIVE_WORD_ERROR, Boolean.FALSE);
    }
    return dynamicContent;
  }

  private String incrCommentQuantity(DynamicCommentCmd cmd) {
    return NumUtils.formatLong(dynamicCacheService.updateCommentQuantity(cmd.getId(), 1));
  }

  private boolean isOwnDynamic(DynamicCommentCmd cmd, DynamicContent dynamicContent) {
    boolean a1 = Objects.isNull(cmd.getToUserId());
    boolean a2 = Objects.equals(dynamicContent.getCreateUser(), cmd.getReqUserId());
    boolean b1 = Objects.equals(cmd.getToUserId(), cmd.getReqUserId());
    return (a1 && a2) || b1;
  }

  private void saveDynamicMessage(DynamicCommentCmd cmd, DynamicMessageEnum type) {

    DynamicMessage message = new DynamicMessage();
    message.setContent(cmd.getContent());
    message.setDynamicContentId(cmd.getId());
    message.setType(type.name());
    message.setToUserId(cmd.getToUserId());
    message.setCreateTime(TimestampUtils.now());
    message.setCreateUser(cmd.getReqUserId());
    message.setId(IdWorkerUtils.getId());
    dynamicMessageService.save(message);

  }

  private void saveComment(DynamicCommentCmd cmd, Long commentId) {

    DynamicComment comment = new DynamicComment();
    comment.setId(commentId);
    comment.setDynamicContentId(cmd.getId());
    comment.setToUserId(cmd.getToUserId());
    comment.setContent(cmd.getContent());
    comment.setCreateTime(TimestampUtils.now());
    comment.setCreateUser(cmd.getReqUserId());
    if (Objects.nonNull(cmd.getToUserId())) {
      comment.setRootCommentId(cmd.getRootCommentId());
    }
    dynamicCommentService.save(comment);

  }

  private boolean isNotBlank(DynamicCommentCmd cmd) {
    return StringUtils.isNotBlank(cmd.getContent().replaceAll(" ", ""));
  }


}
