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

import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.other.infra.database.rds.dao.family.FamilyBoxDailyDAO;
import com.red.circle.other.infra.database.rds.entity.family.FamilyBoxDaily;
import com.red.circle.other.infra.database.rds.service.family.FamilyBoxDailyService;
import java.time.LocalDate;
import java.util.Objects;

import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

/**
 * 家族宝箱每日记录 服务实现类.
 */
@Service
public class FamilyBoxDailyServiceImpl extends BaseServiceImpl<FamilyBoxDailyDAO, FamilyBoxDaily> 
    implements FamilyBoxDailyService {

  @Override
  public FamilyBoxDaily getByFamilyAndDate(Long familyId, LocalDate boxDate) {
    return query()
        .eq(FamilyBoxDaily::getFamilyId, familyId)
        .eq(FamilyBoxDaily::getBoxDate, boxDate)
        .getOne();
  }

  @Override
  public void incrementContributeCount(Long familyId, LocalDate boxDate, String sysOrigin) {
    // 先尝试更新
    if (!tryUpdate(familyId, boxDate)) {
      try {
        FamilyBoxDaily record = new FamilyBoxDaily()
                .setFamilyId(familyId)
                .setBoxDate(boxDate)
                .setSysOrigin(sysOrigin)
                .setContributeCount(1);
        save(record);
      } catch (DuplicateKeyException ignored) {
        tryUpdate(familyId, boxDate);
      }
    }
  }

  private boolean tryUpdate(Long familyId, LocalDate boxDate) {
    return update()
            .setSql("contribute_count = contribute_count + 1")
            .eq(FamilyBoxDaily::getFamilyId, familyId)
            .eq(FamilyBoxDaily::getBoxDate, boxDate)
            .execute();
  }

}
