package com.red.circle.other.infra.database.rds.service.user.user.impl;

import com.red.circle.framework.dto.PageResult;
import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.text.StringUtils;
import com.red.circle.other.infra.database.rds.dao.user.user.InviteWithdrawTransitBalanceDAO;
import com.red.circle.other.infra.database.rds.entity.user.user.InviteWithdrawTransitBalance;
import com.red.circle.other.infra.database.rds.service.user.user.InviteWithdrawTransitBalanceService;
import com.red.circle.other.inner.model.cmd.user.invite.InviteBalancePageQryCmd;
import java.math.BigDecimal;
import java.util.Objects;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 邀请新用户-提现中转账户 服务实现类.
 * </p>
 *
 * @author pengshigang on 2023-12-05 18:10
 */
@AllArgsConstructor
@Service
public class InviteWithdrawTransitBalanceServiceImpl extends
    BaseServiceImpl<InviteWithdrawTransitBalanceDAO, InviteWithdrawTransitBalance> implements
    InviteWithdrawTransitBalanceService {

  @Override
  public boolean decr(Long id, String sysOrigin, BigDecimal expenditure) {

    if (Objects.isNull(getById(id))) {
      add(id, sysOrigin);
    }

    return update().setSql("expenditure_balance=expenditure_balance+" + expenditure)
        .eq(InviteWithdrawTransitBalance::getId, id)
        .apply("income_amount>=expenditure_balance+" + expenditure)
        .last(PageConstant.LIMIT_ONE)
        .execute();

  }

  @Override
  public boolean incr(Long id, String sysOrigin, BigDecimal income) {

    if (Objects.isNull(getById(id))) {
      add(id, sysOrigin);
    }

    return update().setSql("income_amount=income_amount+" + income)
        .eq(InviteWithdrawTransitBalance::getId, id)
        .last(PageConstant.LIMIT_ONE)
        .execute();
  }

  @Override
  public PageResult<InviteWithdrawTransitBalance> pageWithdrawTransitBalance(
      InviteBalancePageQryCmd cmd) {

    return query()
        .eq(Objects.nonNull(cmd.getUserId()), InviteWithdrawTransitBalance::getId,
            cmd.getUserId())
        .eq(StringUtils.isNotBlank(cmd.getSysOrigin()),
            InviteWithdrawTransitBalance::getSysOrigin,
            cmd.getSysOrigin())
        .orderByDesc(InviteWithdrawTransitBalance::getCreateTime)
        .page(cmd.getPageQuery());
  }

  private void add(Long id, String sysOrigin) {
    InviteWithdrawTransitBalance balance = new InviteWithdrawTransitBalance();
    balance.setExpenditureBalance(BigDecimal.ZERO);
    balance.setIncomeAmount(BigDecimal.ZERO);
    balance.setSysOrigin(sysOrigin);
    balance.setCreateUser(id);
    balance.setId(id);
    balance.setCreateTime(TimestampUtils.now());
    super.save(balance);
  }

}
