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

import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.inner.endpoint.user.region.RegionAssistConfigClient;
import com.red.circle.other.inner.endpoint.user.region.RegionConfigClient;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import com.red.circle.other.inner.enums.user.RegionAssistTypeEnum;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.other.inner.model.dto.user.reigon.RegionConfigDTO;
import com.red.circle.tool.core.parse.DataTypeUtils;
import com.red.circle.tool.core.regex.RegexConstant;
import com.red.circle.tool.core.text.StringUtils;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 提现手续费比例
 *
 * @author zongpubin on 2024/3/15
 */
@Component
@RequiredArgsConstructor
public class UserBankWithdrawalServiceChargeQryExe {

  private final UserProfileClient userProfileClient;
  private final RegionConfigClient regionConfigClient;
  private final RegionAssistConfigClient regionAssistConfigClient;

  public Long execute(AppExtCommand cmd) {

    UserProfileDTO userProfile = ResponseAssert.requiredSuccess(
        userProfileClient.getByUserId(cmd.getReqUserId()));
    if (Objects.isNull(userProfile)) {
      return 100L;
    }

    RegionConfigDTO regionConfig = ResponseAssert.requiredSuccess(
        regionConfigClient.getRegionByUserId(userProfile.getId())
    );
    if (Objects.isNull(regionConfig)) {
      return 100L;
    }

    return getAssistDiamondConfig(regionConfig.getId(),
        RegionAssistTypeEnum.WITHDRAWAL_COMMISSION_RATIO);
  }

  private Long getAssistDiamondConfig(String regionId, RegionAssistTypeEnum type) {

    String assistConfigData = ResponseAssert.requiredSuccess(
        regionAssistConfigClient.getAssistConfigData(
            type, regionId)
    );

    if (StringUtils.isBlank(assistConfigData)) {
      return 100L;
    }

    if (!assistConfigData.matches(RegexConstant.NUMBER)) {
      return 100L;
    }

    Long data = DataTypeUtils.toLong(assistConfigData);
    if (Objects.isNull(data) || data <= 0) {
      return 100L;
    }
    return data;
  }
}
