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

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.framework.core.response.ResponseErrorCode;
import com.red.circle.mq.business.model.event.BadgeOperateEvent;
import com.red.circle.mq.business.model.event.task.TaskApprovalEvent;
import com.red.circle.mq.rocket.business.producer.TaskMqMessage;
import com.red.circle.mq.rocket.business.producer.UserMqMessageService;
import com.red.circle.other.app.dto.cmd.team.DbInviteMessageProcessCmd;
import com.red.circle.other.infra.database.cache.service.team.BdTeamCacheService;
import com.red.circle.other.infra.database.mongo.entity.team.bd.BdInviteAgentMessage;
import com.red.circle.other.infra.database.mongo.entity.team.bd.MessageInviteGroup;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamApplicationProcessApproval;
import com.red.circle.other.infra.database.mongo.service.team.bd.BdInviteAgentMessageService;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamApplicationProcessApprovalService;
import com.red.circle.other.infra.database.rds.entity.team.BusinessDevelopmentBaseInfo;
import com.red.circle.other.infra.database.rds.entity.team.RoomBdLead;
import com.red.circle.other.infra.database.rds.service.sys.AdministratorService;
import com.red.circle.other.infra.database.rds.service.team.BusinessDevelopmentBaseInfoService;
import com.red.circle.other.infra.database.rds.service.team.RoomBdLeadService;
import com.red.circle.other.infra.database.rds.service.team.UserHistoryIdentityService;
import com.red.circle.other.inner.enums.material.BadgeKeyEnum;
import com.red.circle.other.inner.asserts.team.TeamErrorCode;
import com.red.circle.other.inner.enums.team.TeamAppProcessApprovalReason;
import com.red.circle.other.inner.enums.team.TeamApplicationType;
import com.red.circle.tool.core.date.LocalDateTimeUtils;
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.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 处理bd leader邀请消息.
 *
 * @author pengshigang on 2023/4/10
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class BdLeaderInviteMessageProcessExe {

  private final RoomBdLeadService roomBdLeadService;
  private final UserHistoryIdentityService userHistoryIdentityService;
  private final BdInviteAgentMessageService bdInviteAgentMessageService;
  private final BusinessDevelopmentBaseInfoService businessDevelopmentBaseInfoService;
  private final TeamApplicationProcessApprovalService teamApplicationProcessApprovalService;
  private final UserMqMessageService userMqMessageService;
  private final AdministratorService administratorService;
  private final TaskMqMessage taskMqMessage;
  private final BdTeamCacheService bdTeamCacheService;

  public void execute(DbInviteMessageProcessCmd cmd) {
    ResponseAssert.isTrue(ResponseErrorCode.REQUEST_PARAMETER_ERROR, cmd.getStatus() > 0);
    BdInviteAgentMessage message = bdInviteAgentMessageService.getById(cmd.getId());
    ResponseAssert.notNull(CommonErrorCode.NOT_FOUND_RECORD_INFO, message);

    ResponseAssert.isTrue(CommonErrorCode.NOT_FOUND_RECORD_INFO,
        Objects.equals(message.getGroup(), MessageInviteGroup.BD_LEADER_INVITE_BD.name()));

    ResponseAssert
        .isFalse(TeamErrorCode.USER_IS_BD,
            roomBdLeadService.checkBdLeader(cmd.requiredReqUserId()));

    ResponseAssert.isFalse(TeamErrorCode.USER_IS_BD,
        businessDevelopmentBaseInfoService.checkBD(cmd.requiredReqUserId()));

    ResponseAssert.isTrue(CommonErrorCode.INSUFFICIENT_PERMISSION,
        Objects.equals(message.getInviteUserId(), cmd.requiredReqUserId()));
    ResponseAssert.isTrue(TeamErrorCode.MESSAGE_PROCESSED, Objects.equals(message.getStatus(), 0));

    RoomBdLead roomBdLead = roomBdLeadService.getByUserId(message.getUserId());
    ResponseAssert.notNull(TeamErrorCode.USER_IS_NOT_BD, roomBdLead);

    ResponseAssert.isTrue(CommonErrorCode.OPERATING_FAILURE, bdInviteAgentMessageService.
        updateStatus(cmd.getId(), message.getStatus(), cmd.getStatus(),
            MessageInviteGroup.BD_LEADER_INVITE_BD.name()));

    if (Objects.equals(cmd.getStatus(), 1)) {

      // 创建BD
      businessDevelopmentBaseInfoService.add(new BusinessDevelopmentBaseInfo()
          .setSysOrigin(cmd.requireReqSysOrigin())
          .setBdLeadUserId(message.getUserId())
          .setUserId(cmd.requiredReqUserId())
          .setRegion(roomBdLead.getRegionId())
          .setContact(StringUtils.isBlank(cmd.getContact()) ? StringUtils.EMPTY : cmd.getContact())
      );

      teamApplicationProcessApprovalService.add(new TeamApplicationProcessApproval()
          .setSysOrigin(cmd.requireReqSysOrigin())
          .setType(TeamApplicationType.BD)
          .setReason(TeamAppProcessApprovalReason.ACCEPT_BD_INVITE)
          .setAssociateId(message.getUserId())
          .setBeProcessUserId(message.getInviteUserId())
          .setCreateTime(TimestampUtils.now())
          .setCreateUser(cmd.requiredReqUserId())
          .setCreateUserOrigin(0)
      );

      userHistoryIdentityService.saveBd(cmd.requiredReqUserId());
      bdTeamCacheService.clearRelationChangeCaches(
          message.getUserId(),
          message.getUserId(),
          cmd.requiredReqUserId());

      // 发送管理员任务消息
      sendAdminTaskMessage(message.getUserId(), 14);

      userMqMessageService.sendBadgeOperateEvent(cmd.requiredReqUserId(), BadgeKeyEnum.BD.name(), BadgeOperateEvent.OperationType.WEAR.name());
    }
  }

    private void sendAdminTaskMessage(Long userId, Integer taskId) {
        boolean admin = administratorService.existsAdmin(userId);
        if (admin) {
            taskMqMessage.sendTask(TaskApprovalEvent.builder()
                    .taskId(taskId)
                    .userId(userId)
                    .day(LocalDateTimeUtils.nowFormat("yyyy-MM-dd"))
                    .build());
        }
    }

  public void executeBdleader(DbInviteMessageProcessCmd cmd) {
    ResponseAssert.isTrue(ResponseErrorCode.REQUEST_PARAMETER_ERROR, cmd.getStatus() > 0);
    BdInviteAgentMessage message = bdInviteAgentMessageService.getById(cmd.getId());
    ResponseAssert.notNull(CommonErrorCode.NOT_FOUND_RECORD_INFO, message);

    ResponseAssert.isTrue(CommonErrorCode.NOT_FOUND_RECORD_INFO,
        Objects.equals(message.getGroup(), MessageInviteGroup.BD_LEADER_INVITE_BD_LEADER.name()));

    ResponseAssert.isFalse(TeamErrorCode.USER_IS_ALREADY_A_BDLEADER,
            roomBdLeadService.checkBdLeader(cmd.requiredReqUserId()));
    ResponseAssert.isFalse(TeamErrorCode.USER_IS_ALREADY_A_BD,
              businessDevelopmentBaseInfoService.checkBD(cmd.requiredReqUserId()));

    ResponseAssert.isTrue(CommonErrorCode.INSUFFICIENT_PERMISSION,
        Objects.equals(message.getInviteUserId(), cmd.requiredReqUserId()));
    ResponseAssert.isTrue(TeamErrorCode.MESSAGE_PROCESSED, Objects.equals(message.getStatus(), 0));

    RoomBdLead roomBdLead = roomBdLeadService.getByUserId(message.getUserId());
    ResponseAssert.notNull(TeamErrorCode.USER_IS_NOT_BD, roomBdLead);

    ResponseAssert.isTrue(CommonErrorCode.OPERATING_FAILURE, bdInviteAgentMessageService.
        updateStatus(cmd.getId(), message.getStatus(), cmd.getStatus(),
            MessageInviteGroup.BD_LEADER_INVITE_BD_LEADER.name()));

    if (Objects.equals(cmd.getStatus(), 1)) {
        // 创建BD
        RoomBdLead bdLead = new RoomBdLead();
        bdLead.setId(IdWorkerUtils.getId());
        bdLead.setUserId(cmd.requiredReqUserId());
        bdLead.setSysOrigin(roomBdLead.getSysOrigin());
        bdLead.setRegionId(roomBdLead.getRegionId());
        bdLead.setCreateUser(cmd.requiredReqUserId());
        roomBdLeadService.save(bdLead);

        businessDevelopmentBaseInfoService.add(new BusinessDevelopmentBaseInfo()
                .setSysOrigin(cmd.requireReqSysOrigin())
                .setBdLeadUserId(message.getUserId())
                .setUserId(cmd.requiredReqUserId())
                .setRegion(roomBdLead.getRegionId())
                .setContact(StringUtils.isBlank(cmd.getContact()) ? StringUtils.EMPTY : cmd.getContact())
        );

      teamApplicationProcessApprovalService.add(new TeamApplicationProcessApproval()
          .setSysOrigin(cmd.requireReqSysOrigin())
          .setType(TeamApplicationType.BD)
          .setReason(TeamAppProcessApprovalReason.ACCEPT_BDLEADER_INVITE)
          .setAssociateId(message.getUserId())
          .setBeProcessUserId(message.getInviteUserId())
          .setCreateTime(TimestampUtils.now())
          .setCreateUser(cmd.requiredReqUserId())
          .setCreateUserOrigin(0)
      );

      bdTeamCacheService.clearRelationChangeCaches(
          message.getUserId(),
          message.getUserId(),
          cmd.requiredReqUserId());
      bdTeamCacheService.clearLeaderRelatedCaches(cmd.requiredReqUserId());

      // 发送管理员任务消息
      sendAdminTaskMessage(message.getUserId(), 13);

      userMqMessageService.sendBadgeOperateEvent(cmd.requiredReqUserId(), BadgeKeyEnum.BD.name(), BadgeOperateEvent.OperationType.WEAR.name());
      userMqMessageService.sendBadgeOperateEvent(cmd.requiredReqUserId(), BadgeKeyEnum.BD_LEADER.name(), BadgeOperateEvent.OperationType.WEAR.name());

    }
  }


}
