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.FamilyMessageDAO;
import com.red.circle.other.infra.database.rds.entity.family.FamilyMessage;
import com.red.circle.other.infra.database.rds.service.family.FamilyMessageService;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 家族消息表 服务实现类.
 * </p>
 *
 * @author pengshigang
 * @since 2021-07-20
 */
@Service
public class FamilyMessageServiceImpl extends
    BaseServiceImpl<FamilyMessageDAO, FamilyMessage> implements FamilyMessageService {

  @Override
  public List<FamilyMessage> listUntreatedById(Long familyId, Long lastId) {
    return Optional.ofNullable(query()
        .eq(FamilyMessage::getFamilyId, familyId)
        .eq(FamilyMessage::getStatus, Boolean.FALSE)
        .lt(Objects.nonNull(lastId), FamilyMessage::getId, lastId)
        .orderByDesc(FamilyMessage::getId)
        .last(PageConstant.DEFAULT_LIMIT)
        .list()).orElse(CollectionUtils.newArrayList());
  }

  @Override
  public Boolean isExistApplyingMsg(Long familyId, Long userId) {
    return Objects.nonNull(query()
        .eq(FamilyMessage::getFamilyId, familyId)
        .eq(FamilyMessage::getSenderUser, userId)
        .eq(FamilyMessage::getStatus, Boolean.FALSE)
        .getOne());
  }

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


  @Override
  public void deleteByFamilyIdByUserId(Long familyId, Long userId) {
    if (Objects.isNull(familyId) || Objects.isNull(userId)) {
      return;
    }
    delete()
        .eq(FamilyMessage::getFamilyId, familyId)
        .eq(FamilyMessage::getApproveUser, userId)
        .execute();
  }
}
