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.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.date.ZonedDateTimeAsiaRiyadhUtils;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import com.red.circle.other.infra.database.rds.dao.user.user.RecentlyActiveDAO;
import com.red.circle.other.infra.database.rds.entity.user.user.RecentlyActive;
import com.red.circle.other.infra.database.rds.service.user.user.RecentlyActiveService;
import java.sql.Timestamp;
import java.util.List;
import java.util.Objects;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户最近活跃时间.
 * </p>
 *
 * @author pengshigang on 2023-12-29 18:10
 */
@AllArgsConstructor
@Service
public class RecentlyActiveServiceImpl extends
    BaseServiceImpl<RecentlyActiveDAO, RecentlyActive> implements RecentlyActiveService {
  private final UserProfileGateway userProfileGateway;
  @Override
  public void add(String sysOrigin, Long userId) {

    Integer dateNumber = ZonedDateTimeAsiaRiyadhUtils.nowDateToInt();

    List<RecentlyActive> getRecentlyActiveTwo = getRecentlyActiveTwo(userId);
    if (CollectionUtils.isEmpty(getRecentlyActiveTwo)) {
      addData(sysOrigin, userId, dateNumber);
      return;
    }

    // 存在今天数据则不再添加
    if (getRecentlyActiveTwo.stream()
        .anyMatch(v -> Objects.equals(v.getDateNumber(), dateNumber))) {
      return;
    }

    // 只有一条数据则继续添加一条
    if (getRecentlyActiveTwo.size() <= 1) {
      addData(sysOrigin, userId, dateNumber);
      return;
    }

    // 存在多条数据则只保留最新一条记录,其他的删除. 每个用户最多保存两条记录.
    RecentlyActive recentlyActive = getRecentlyActiveTwo.get(0);
    delete()
        .eq(RecentlyActive::getUserId, userId)
        .lt(RecentlyActive::getDateNumber, recentlyActive.getDateNumber())
        .execute();

    addData(sysOrigin, userId, dateNumber);
  }

  private List<RecentlyActive> getRecentlyActiveTwo(Long userId) {
    return query()
        .eq(RecentlyActive::getUserId, userId)
        .orderByDesc(RecentlyActive::getCreateTime)
        .last(PageConstant.formatLimit(2))
        .list();
  }

  @Override
  public Timestamp getLastActiveTime(Long userId) {

    List<RecentlyActive> getRecentlyActiveTwo = getRecentlyActiveTwo(userId);
    if (CollectionUtils.isEmpty(getRecentlyActiveTwo)||getRecentlyActiveTwo.size() <= 1) {
      UserProfile userProfile = userProfileGateway.getByUserId(userId);
      if (userProfile == null) {
        return null;
      }
      long time = Objects.nonNull(userProfile.getCreateTime()) ? TimestampUtils.durationNowDays(
              userProfile.getCreateTime()) : 1L;
      if(time<1){
        return null;
      }
    }
    return getRecentlyActiveTwo.get(1).getCreateTime();
  }

  private void addData(String sysOrigin, Long userId, Integer dateNumber) {

    RecentlyActive recentlyActive = new RecentlyActive();
    recentlyActive.setId(IdWorkerUtils.getId());
    recentlyActive.setUserId(userId);
    recentlyActive.setSysOrigin(sysOrigin);
    recentlyActive.setDateNumber(dateNumber);
    recentlyActive.setCreateTime(TimestampUtils.now());
    recentlyActive.setCreateUser(userId);
    super.save(recentlyActive);
  }

}
