package com.red.circle.other.infra.database.mongo.service.team.team.impl;

import com.mongodb.BasicDBObject;
import com.mongodb.client.model.Filters;
import com.red.circle.component.mongodb.config.MongoPrimaryService;
import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamExchangeSurplusTarget;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamExchangeSurplusTargetService;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import java.util.List;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.GroupOperation;
import org.springframework.data.mongodb.core.aggregation.MatchOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

/**
 * 将主播剩余目标兑换成美元记录.
 *
 * @author pengliang on 2022/12/13
 */
@Service
@RequiredArgsConstructor
public class TeamExchangeSurplusTargetServiceImpl implements TeamExchangeSurplusTargetService {

  private final MongoTemplate mongoTemplate;
  private final MongoPrimaryService mongoPrimaryService;

  @Override
  public List<TeamExchangeSurplusTarget> listByCondition(Long lastId, Long userId, String sysOrigin,
      Integer dateNumber) {

    Criteria criteria = Criteria.where("sysOrigin").is(sysOrigin);

    if (Objects.nonNull(userId)) {
      criteria.and("userId").is(userId);
    }

    if (Objects.nonNull(dateNumber) && dateNumber > 0) {
      criteria.and("dateNumber").is(dateNumber);
    }

    if (Objects.nonNull(lastId)) {
      criteria.and("id").lt(lastId);
    }

    return mongoTemplate.find(Query.query(criteria)
            .with(Sort.by(Sort.Order.desc("id")))
            .limit(PageConstant.DEFAULT_LIMIT_SIZE),
        TeamExchangeSurplusTarget.class);

  }

  @Override
  public void add(TeamExchangeSurplusTarget param) {

    param.setId(IdWorkerUtils.getId());
    param.setCreateTime(TimestampUtils.now());
    param.setExpiredTime(TimestampUtils.nowPlusDays(150));
    mongoTemplate.save(param);

  }

  @Override
  public Boolean exist(Long userId, Integer dateNumber) {

    return mongoPrimaryService.exists("team_exchange_surplus_target",
        Filters.and(
            Filters.eq("userId", userId),
            Filters.eq("dateNumber", dateNumber)
        )
    );
  }

  @Override
  public String getTotalAmountUsd(Long userId, String sysOrigin, Integer dateNumber) {

    Criteria criteria = Criteria.where("sysOrigin").is(sysOrigin);

    if (Objects.nonNull(userId)) {
      criteria.and("userId").is(userId);
    }
    if (Objects.nonNull(dateNumber) && dateNumber > 0) {
      criteria.and("dateNumber").is(dateNumber);
    }

    // 构造聚合管道
    MatchOperation matchOperation = Aggregation.match(criteria);
    GroupOperation groupOperation = Aggregation.group().sum("amountUsd").as("totalAmount");
    Aggregation aggregation = Aggregation.newAggregation(matchOperation, groupOperation);

    AggregationResults<BasicDBObject> aggregationResults = mongoTemplate.aggregate(aggregation,
        TeamExchangeSurplusTarget.class, BasicDBObject.class);

    List<BasicDBObject> basicDBObjectList = aggregationResults.getMappedResults();

    if (CollectionUtils.isNotEmpty(basicDBObjectList)) {
      return basicDBObjectList.get(0).getString("totalAmount");
    }
    return "0";
  }

}
