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

import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.other.infra.database.rds.dao.family.FamilyMonthExpDAO;
import com.red.circle.other.infra.database.rds.entity.family.FamilyMonthExp;
import com.red.circle.other.infra.database.rds.service.family.FamilyMonthExpService;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.date.LocalDateUtils;
import com.red.circle.tool.core.text.StringUtils;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 家族每月贡献值榜单 服务实现类.
 * </p>
 *
 * @author pengshigang
 * @since 2021-07-21
 * @since pengliang 2022-8-4 modify
 */
@Service
public class FamilyMonthExpServiceImpl extends
    BaseServiceImpl<FamilyMonthExpDAO, FamilyMonthExp> implements FamilyMonthExpService {

  @Override
  public void incrThisMonthExp(String sysOrigin, Long familyId, String regionId, Long exp) {

    if (StringUtils.isBlank(sysOrigin) || Objects.isNull(familyId) || exp <= 0) {
      return;
    }

    Integer dateSplit = LocalDateUtils.nowThisMonthToInteger();
    FamilyMonthExp existsFamily = query()
        .select(FamilyMonthExp::getId)
        .eq(FamilyMonthExp::getFamilyId, familyId)
        .eq(FamilyMonthExp::getSysOrigin, sysOrigin)
        .eq(FamilyMonthExp::getDateSplit, dateSplit)
        .last(PageConstant.LIMIT_ONE)
        .getOne();

    if (Objects.isNull(existsFamily) || Objects.isNull(existsFamily.getId())) {
      super.save(new FamilyMonthExp()
          .setSysOrigin(sysOrigin)
          .setRegions(regionId)
          .setFamilyId(familyId)
          .setExp(exp)
          .setDateSplit(dateSplit)
      );
      return;
    }

    update()
        .setSql("exp=exp+" + exp)
        .eq(FamilyMonthExp::getId, existsFamily.getId())
        .execute();
  }

  @Override
  public List<FamilyMonthExp> listThisMonthBySysOrigin(String sysOrigin, String regionId) {
    return Optional.ofNullable(
            query()
                .eq(FamilyMonthExp::getSysOrigin, sysOrigin)
                .eq(FamilyMonthExp::getRegions, regionId)
                .eq(FamilyMonthExp::getDateSplit, LocalDateUtils.nowThisMonthToInteger())
                .orderByDesc(FamilyMonthExp::getExp)
                .list())
        .orElse(CollectionUtils.newArrayList());
  }

  @Override
  public FamilyMonthExp getThisMonthByFamilyId(Long familyId) {
    return query()
        .eq(FamilyMonthExp::getFamilyId, familyId)
        .eq(FamilyMonthExp::getDateSplit, LocalDateUtils.nowThisMonthToInteger())
        .last(PageConstant.LIMIT_ONE)
        .getOne();
  }

  @Override
  public void deleteByFamilyId(Long familyId) {
    if (Objects.isNull(familyId)) {
      return;
    }
    delete().eq(FamilyMonthExp::getFamilyId, familyId).execute();
  }
}
