package com.red.circle.other.app.inner.service.team.impl;

import com.red.circle.other.app.inner.service.team.UserBillDiamondBalanceClientService;
import com.red.circle.other.infra.convertor.team.TeamInfraConvertor;
import com.red.circle.other.infra.database.rds.service.team.BillDiamondBalanceDetailsService;
import com.red.circle.other.infra.database.rds.service.team.BillDiamondBalanceService;
import com.red.circle.other.inner.model.dto.agency.agency.BillDiamondBalanceDTO;
import com.red.circle.tool.core.date.ZonedDateTimeAsiaRiyadhUtils;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * 用户账单钻石余额.
 *
 * @author xiaofei on 2023/10/17
 */
@Service
@RequiredArgsConstructor
public class UserBillDiamondBalanceClientServiceImpl implements UserBillDiamondBalanceClientService {

  private static final Logger log = LoggerFactory.getLogger(UserBillDiamondBalanceClientServiceImpl.class);
  private final TeamInfraConvertor teamInfraConvertor;
  private final BillDiamondBalanceService billDiamondBalanceService;
  private final BillDiamondBalanceDetailsService billDiamondBalanceDetailsService;

  @Override
  public BillDiamondBalanceDTO getEntityByBillBelongAndUserId(String sysOrigin, Integer billBelong, Long userId) {
    return teamInfraConvertor.toBillDiamondBalanceDTO(
            billDiamondBalanceService.getEntityByBillBelongAndUserId(sysOrigin, billBelong, userId)
    );
  }

  @Override
  public BillDiamondBalanceDTO decr(Long userId, Integer billBelong, BigDecimal amount) {
    // 同步修改日账单
    try {
      billDiamondBalanceDetailsService.decrBillBelongDay(userId, amount, ZonedDateTimeAsiaRiyadhUtils.nowDateToInt());
    }catch (Exception e) {
      log.error("Failed to decr billBelongDay", e);
    }
    return teamInfraConvertor.toBillDiamondBalanceDTO(
            billDiamondBalanceService.decr(userId, amount, billBelong));
  }

  @Override
  public BillDiamondBalanceDTO decrAgent(Long userId, Integer billBelong, BigDecimal amount) {
    // 同步修改日账单
    try {
      billDiamondBalanceDetailsService.decrAgentBillBelongDay(userId, amount, ZonedDateTimeAsiaRiyadhUtils.nowDateToInt());
    }catch (Exception e) {
      log.error("Failed to decrAgent billBelongDay", e);
    }
    return teamInfraConvertor.toBillDiamondBalanceDTO(
            billDiamondBalanceService.decrAgent(userId, amount, billBelong));
  }

}
