package com.red.circle.console.infra.database.rds.service.count.impl;

import com.google.common.collect.Maps;
import com.red.circle.console.infra.database.rds.dao.count.StatisticsMonthlyPurchaseAmountPlatformDAO;
import com.red.circle.console.infra.database.rds.entity.count.StatisticsMonthlyPurchaseAmountPlatform;
import com.red.circle.console.infra.database.rds.service.count.StatisticsMonthlyPurchaseAmountPlatformService;
import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 平台每月内购量 服务实现类
 * </p>
 *
 * @author pengliang
 * @since 2022-03-08
 */
@Service
@RequiredArgsConstructor
public class StatisticsMonthlyPurchaseAmountPlatformServiceImpl extends
    BaseServiceImpl<StatisticsMonthlyPurchaseAmountPlatformDAO, StatisticsMonthlyPurchaseAmountPlatform> implements
    StatisticsMonthlyPurchaseAmountPlatformService {

  @Override
  public List<StatisticsMonthlyPurchaseAmountPlatform> listLatestMonth(Integer latestMonth) {
    return query()
        .gt(StatisticsMonthlyPurchaseAmountPlatform::getStatisticsTime,
            LocalDateTime.now().minusMonths(latestMonth))
        .orderByAsc(StatisticsMonthlyPurchaseAmountPlatform::getDateNumber)
        .list();
  }

  @Override
  public void inrOfflineQuantity(String sysOrigin, Integer dateNumber, BigDecimal quantity) {
    update()
        .setSql("offline_quantity=IF(offline_quantity IS NULL, 0, offline_quantity)+" + quantity)
        .eq(StatisticsMonthlyPurchaseAmountPlatform::getSysOrigin, sysOrigin)
        .eq(StatisticsMonthlyPurchaseAmountPlatform::getDateNumber, dateNumber)
        .last(PageConstant.LIMIT_ONE)
        .execute();
  }

  @Override
  public Map<String, List<StatisticsMonthlyPurchaseAmountPlatform>> mapAllSysOrigin(
      Integer latestMonth) {
    return Optional.ofNullable(listLatestMonth(
            latestMonth))
        .map(platforms -> platforms.stream()
            .collect(Collectors.groupingBy(StatisticsMonthlyPurchaseAmountPlatform::getSysOrigin)))
        .orElse(Maps.newHashMap());
  }

}
