package com.red.circle.wallet.infra.database.mongo.service.bank.impl;

import com.google.common.collect.Maps;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.text.StringUtils;
import com.red.circle.wallet.infra.database.mongo.entity.bank.UserBankWithdrawGoldApply;
import com.red.circle.wallet.infra.database.mongo.service.bank.UserBankWithdrawGoldApplyService;
import com.red.circle.wallet.inner.model.cmd.UserBankWithdrawGoldApplyQryCmd;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

/**
 * 用户银行卡提现金币申请记录 实现.
 *
 * @author pengliang on 2023/2/15
 */
@Service
@RequiredArgsConstructor
public class UserBankWithdrawGoldApplyServiceImpl implements UserBankWithdrawGoldApplyService {

  private final MongoTemplate mongoTemplate;

  @Override
  public void add(UserBankWithdrawGoldApply apply) {
    mongoTemplate.save(apply);
  }

  @Override
  public Map<Long, UserBankWithdrawGoldApply> mapByIds(Set<Long> ids) {

    if (CollectionUtils.isEmpty(ids)) {
      return Maps.newHashMap();
    }

    List<UserBankWithdrawGoldApply> applies = mongoTemplate.find(
        Query.query(Criteria.where("id").in(ids)),
        UserBankWithdrawGoldApply.class);

    if (CollectionUtils.isEmpty(applies)) {
      return Maps.newHashMap();
    }

    return applies.stream().collect(Collectors.toMap(UserBankWithdrawGoldApply::getId, v -> v));
  }

  @Override
  public List<UserBankWithdrawGoldApply> pageBankWithdrawGoldApply(
      UserBankWithdrawGoldApplyQryCmd query) {

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

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

    if (Objects.nonNull(query.getAcceptUserId())) {
      criteria.and("acceptUserId").is(query.getAcceptUserId());
    }

    if (Objects.nonNull(query.getSubmitUserId())) {
      criteria.and("submitUserId").is(query.getSubmitUserId());
    }

    if (StringUtils.isNotBlank(query.getAcceptAccount())) {
      criteria.and("acceptAccount").is(query.getAcceptAccount());
    }

    if (Objects.nonNull(query.getStartTime()) && Objects.nonNull(query.getEndTime())) {
      criteria.andOperator(
          Criteria.where("createTime").gte(query.getStartTime()),
          Criteria.where("createTime").lte(query.getEndTime())
      );
    }

    return mongoTemplate.find(Query.query(criteria)
            .with(Sort.by(Sort.Order.desc("id")))
            .limit(query.getLimit()),
        UserBankWithdrawGoldApply.class);
  }

}
