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.text.StringUtils;
import com.red.circle.other.infra.database.rds.dao.user.user.GiveFriendshipCardApplyDAO;
import com.red.circle.other.infra.database.rds.entity.user.user.GiveFriendshipCardApply;
import com.red.circle.other.infra.database.rds.service.user.user.GiveFriendshipCardApplyService;
import com.red.circle.other.infra.enums.user.user.CpApplyStatus;
import java.util.List;
import java.util.Objects;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户赠送友谊关系卡记录 服务实现类.
 * </p>
 *
 * @author pengshigang
 * @since 2022-06-09
 */
@Service
public class GiveFriendshipCardApplyServiceImpl extends
    BaseServiceImpl<GiveFriendshipCardApplyDAO, GiveFriendshipCardApply> implements
    GiveFriendshipCardApplyService {

  @Override
  public Boolean exist(String type, Long sendUserId, Long acceptUserId) {

    GiveFriendshipCardApply apply = query()
        .eq(GiveFriendshipCardApply::getCardType, type)
        .eq(GiveFriendshipCardApply::getAcceptUserId, acceptUserId)
        .eq(GiveFriendshipCardApply::getSendUserId, sendUserId)
        .last(PageConstant.LIMIT_ONE)
        .getOne();

    if (Objects.isNull(apply)) {
      return Boolean.FALSE;
    }
    return Objects.equals(apply.getStatus(), CpApplyStatus.WAIT.name());
  }

  @Override
  public Boolean changeStatusById(Long id, String status) {

    return update()
        .set(GiveFriendshipCardApply::getStatus, status)
        .eq(GiveFriendshipCardApply::getId, id)
        .last(PageConstant.LIMIT_ONE)
        .execute();
  }

  @Override
  public List<GiveFriendshipCardApply> pageByCondition(Integer pageNumber, String type,
      Long userId) {

    if (Objects.isNull(pageNumber) || pageNumber < 1) {
      pageNumber = 1;
    }

    return query()
        .eq(GiveFriendshipCardApply::getAcceptUserId, userId)
        .eq(StringUtils.isNotBlank(type), GiveFriendshipCardApply::getCardType, type)
        .eq(GiveFriendshipCardApply::getStatus, CpApplyStatus.WAIT.name())
        .orderByDesc(GiveFriendshipCardApply::getCreateTime)
        .last(getPageSql(pageNumber))
        .list();
  }

  @Override
  public Long countFriendshipCardApply(Long userId) {

    return query()
        .eq(GiveFriendshipCardApply::getAcceptUserId, userId)
        .eq(GiveFriendshipCardApply::getStatus, CpApplyStatus.WAIT.name())
        .count();
  }

  private String getPageSql(Integer pageNumber) {

    return String.format("LIMIT %s, %s", (pageNumber - 1) * PageConstant.DEFAULT_LIMIT_SIZE,
        PageConstant.DEFAULT_LIMIT_SIZE);
  }

}
