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

import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import com.red.circle.other.infra.database.cache.service.user.RedPacketInviteUserCacheService;
import com.red.circle.other.infra.database.rds.dao.user.user.InviteCarouselAwardsDAO;
import com.red.circle.other.infra.database.rds.entity.user.user.InviteCarouselAwards;
import com.red.circle.other.infra.database.rds.service.user.user.InviteCarouselAwardsService;
import com.red.circle.other.inner.model.cmd.user.invite.InviteCarouselAwardsCmd;
import java.util.List;
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 InviteCarouselAwardsServiceImpl extends
    BaseServiceImpl<InviteCarouselAwardsDAO, InviteCarouselAwards> implements
    InviteCarouselAwardsService {

  private final RedPacketInviteUserCacheService redPacketInviteUserCacheService;

  @Override
  public List<InviteCarouselAwards> listBySysOrigin(String sysOrigin) {

    return query()
        .eq(InviteCarouselAwards::getSysOrigin, sysOrigin)
        .last(PageConstant.formatLimit(50))
        .list();
  }

  @Override
  public void saveOrUpd(InviteCarouselAwardsCmd awards) {

    InviteCarouselAwards carouselAwards = getById(awards.getId());
    if (Objects.isNull(carouselAwards)) {

      carouselAwards = new InviteCarouselAwards();
      carouselAwards.setId(IdWorkerUtils.getId());
      carouselAwards.setQuantity(awards.getQuantity());
      carouselAwards.setSysOrigin(awards.getSysOrigin());
      carouselAwards.setType(awards.getType());
      super.save(carouselAwards);
      redPacketInviteUserCacheService.removeCarouselAwardsCache(awards.getSysOrigin());
      return;
    }

    update()
        .set(InviteCarouselAwards::getType, awards.getType())
        .set(Objects.nonNull(awards.getQuantity()), InviteCarouselAwards::getQuantity,
            awards.getQuantity())
        .eq(InviteCarouselAwards::getId, awards.getId())
        .last(PageConstant.LIMIT_ONE)
        .execute();

    if (!Objects.equals(carouselAwards.getQuantity(), awards.getQuantity()) || !Objects.equals(
        carouselAwards.getType(), awards.getType())) {
      redPacketInviteUserCacheService.removeCarouselAwardsCache(awards.getSysOrigin());
    }
  }

  @Override
  public void deleteById(Long id) {

    delete()
        .eq(InviteCarouselAwards::getId, id)
        .last(PageConstant.LIMIT_ONE)
        .execute();

  }

}
