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

import com.red.circle.framework.dto.PageResult;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.tool.core.date.LocalDateUtils;
import com.red.circle.other.infra.database.rds.dao.user.user.ApprovalUserAccountStatusLogDAO;
import com.red.circle.other.infra.database.rds.entity.user.user.ApprovalUserAccountStatusLog;
import com.red.circle.other.infra.database.rds.service.user.user.ApprovalUserAccountStatusLogService;
import com.red.circle.other.inner.model.cmd.user.UserAccountStatusLogQryCmd;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 审批账户历史记录 服务实现类
 * </p>
 *
 * @author pengliang
 * @since 2020-05-16
 */
@Service
public class ApprovalUserAccountStatusLogServiceImpl extends
    BaseServiceImpl<ApprovalUserAccountStatusLogDAO, ApprovalUserAccountStatusLog> implements
    ApprovalUserAccountStatusLogService {

  @Override
  public long countNowFreezeSize(Long userId) {
    LocalDate localDate = LocalDate.now();
    return Optional.ofNullable(
        query()
            .gt(ApprovalUserAccountStatusLog::getCreateTime,
                LocalDateUtils.format(localDate, "yyyy-MM-dd"))
            .lt(ApprovalUserAccountStatusLog::getCreateTime,
                LocalDateUtils.format(localDate.plusDays(1), "yyyy-MM-dd"))
            .eq(ApprovalUserAccountStatusLog::getBeApprovalUser, userId)
            .count()
    ).orElse(0L);
  }


  @Override
  public void saveLog(ApprovalUserAccountStatusLog approvalUserAccountStatusLog) {
    save(approvalUserAccountStatusLog);
  }

  @Override
  public PageResult<ApprovalUserAccountStatusLog> pgeApprovalUserAccountStatusLog(
      UserAccountStatusLogQryCmd cmd) {
    return query()
        .eq(ApprovalUserAccountStatusLog::getBeApprovalUser, cmd.getBeApprovalUser())
        .orderByDesc(ApprovalUserAccountStatusLog::getCreateTime)
        .page(cmd.getPageQuery());
  }

  @Override
  public List<ApprovalUserAccountStatusLog> lastApprovalUserAccountStatusLog(Long beApprovalUser,
      Integer size) {
    return query()
        .eq(ApprovalUserAccountStatusLog::getBeApprovalUser, beApprovalUser)
        .last("LIMIT " + size)
        .orderByDesc(ApprovalUserAccountStatusLog::getCreateTime)
        .list();
  }
}
