package com.red.circle.wallet.app.command.bank.query;

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.inner.endpoint.team.agency.AgentTeamClient;
import com.red.circle.other.inner.endpoint.team.bd.BdTeamInfoClient;
import com.red.circle.other.inner.endpoint.user.region.UserRegionClient;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import com.red.circle.wallet.app.dto.cmd.UserBankSearchUserProfileCmd;
import java.util.Objects;

import com.red.circle.wallet.infra.database.rds.service.freight.FreightBalanceService;
import com.red.circle.wallet.inner.model.enums.UserBankWaterEvent;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 搜索用户.
 *
 * @author pengliang on 2023/2/24
 */
@Component
@RequiredArgsConstructor
public class UserBankSearchUserProfileQryExe {

  private final BdTeamInfoClient bdTeamClient;
  private final AgentTeamClient agentTeamClient;
  private final UserProfileClient userProfileClient;
  private final UserRegionClient userRegionClient;
  private final FreightBalanceService freightBalanceService;

  public UserProfileDTO execute(UserBankSearchUserProfileCmd cmd) {

    UserProfileDTO userProfile = ResponseAssert.requiredSuccess(
        userProfileClient.getByAccount(cmd.requireReqSysOrigin(),
            cmd.getAccount()));

    if (Objects.isNull(userProfile)) {
      return null;
    }
    // 判断是否同一个区域
    Boolean isEqRegion = userRegionClient.checkEqRegion(cmd.requiredReqUserId(), userProfile.getId()).getBody();
    if (!isEqRegion) {
      return null;
    }

    if (isTransfer(cmd)) {
       if (Objects.equals(cmd.getReqUserId(), userProfile.getId())) {
         return null;
       }
    }

    if (cmd.typeEqBD()) {
      return
          Objects.equals(ResponseAssert.requiredSuccess(bdTeamClient.check(userProfile.getId())),
              Boolean.TRUE)
              ? userProfile
              : null;
    }

    if (cmd.typeEqAnchor()) {
      return Objects.equals(
          ResponseAssert.requiredSuccess(agentTeamClient.existsTeamMember(userProfile.getId())),
          Boolean.TRUE)
          ? userProfile
          : null;
    }

    if (cmd.typeEqAgent()) {
      Boolean freightAgent = freightBalanceService.checkFreightAgent(userProfile.getId());
      if (freightAgent) {
        return userProfile;
      }
      if (isTransfer(cmd)) {
          return null;
      }

      return Objects.equals(
          ResponseAssert.requiredSuccess(agentTeamClient.existsTeamOwn(userProfile.getId())),
          Boolean.TRUE)
          ? userProfile
          : null;
    }

    return null;
  }

    private static boolean isTransfer(UserBankSearchUserProfileCmd cmd) {
        return UserBankWaterEvent.TRANSFER.name().equals(cmd.getSearchType());
    }

}
