package com.red.circle.wallet.inner.service.wallet.impl;

import com.red.circle.common.business.dto.cmd.PageUserIdCmd;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.tool.core.text.StringUtils;
import com.red.circle.wallet.domain.gateway.WalletBeanGateway;
import com.red.circle.wallet.domain.wallet.BeanReceipt;
import com.red.circle.wallet.infra.database.rds.service.bean.BeanBalanceService;
import com.red.circle.wallet.infra.database.rds.service.bean.BeanIncomeExpenditureService;
import com.red.circle.wallet.inner.convertor.WalletInnerConvertor;
import com.red.circle.wallet.inner.model.cmd.AddBeanIncomeExpenditureCmd;
import com.red.circle.wallet.inner.model.cmd.BeanReceiptCmd;
import com.red.circle.wallet.inner.model.cmd.UserBeanIncomeExpenditurePageQryCmd;
import com.red.circle.wallet.inner.model.dto.BeanBalanceDTO;
import com.red.circle.wallet.inner.model.dto.UserBeanIncomeExpenditureDTO;
import com.red.circle.wallet.inner.model.dto.WalletReceiptDTO;
import com.red.circle.wallet.inner.service.wallet.WalletBeanClientService;
import java.math.BigDecimal;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author pengliang on 2023/5/26
 */
@Service
@RequiredArgsConstructor
public class WalletBeanClientServiceImpl implements WalletBeanClientService {

  private final WalletBeanGateway walletBeanGateway;
  private final BeanBalanceService walletBeanService;
  private final WalletInnerConvertor walletInnerConvertor;
  private final BeanIncomeExpenditureService beanIncomeExpenditureService;

  @Override
  public BigDecimal getBalance(Long userId) {
    return walletBeanGateway.getBalance(userId);
  }

  @Override
  public WalletReceiptDTO changeBalance(BeanReceiptCmd cmd) {

    BeanReceipt receipt = walletInnerConvertor.toBeanReceipt(cmd);

    receipt.setOriginDesc(
        StringUtils.isBlank(cmd.getCustomizeOriginDesc())
            ? cmd.getOrigin().getDesc()
            : cmd.getCustomizeOriginDesc()
    );

    return walletInnerConvertor.toWalletReceiptDTO(
        walletBeanGateway.changeBalance(receipt));
  }

  @Override
  public PageResult<BeanBalanceDTO> pageBeanBalance(PageUserIdCmd cmd) {
    return walletBeanService.pageBeanBalance(cmd).convert(walletInnerConvertor::toBeanBalanceDTO);
  }

  @Override
  public PageResult<UserBeanIncomeExpenditureDTO> pageRunningWater(
      UserBeanIncomeExpenditurePageQryCmd query) {
    return beanIncomeExpenditureService.pageRunningWater(query)
        .convert(walletInnerConvertor::toUserBeanIncomeExpenditureDTO);
  }


  @Override
  public void saveBeanIncome(AddBeanIncomeExpenditureCmd cmd) {
    beanIncomeExpenditureService.saveBeanIncome(walletInnerConvertor.toBeanIncomeExpenditure(cmd));
  }

}
