package com.czg.service.order.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.czg.order.entity.OrderDetail;
import com.czg.order.service.OrderDetailService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.czg.order.entity.ShopProdStatistic;
import com.czg.order.service.ShopProdStatisticService;
import com.czg.service.order.mapper.ShopProdStatisticMapper;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  服务层实现。
 *
 * @author zs
 * @since 2025-03-07
 */
@Service
public class ShopProdStatisticServiceImpl extends ServiceImpl<ShopProdStatisticMapper, ShopProdStatistic> implements ShopProdStatisticService{
    @Resource
    private OrderDetailService orderDetailService;
    @Data
    private static class StatisticTask{
        private BigDecimal successCount = BigDecimal.ZERO;
        private BigDecimal successAmount = BigDecimal.ZERO;
        private BigDecimal refundCount = BigDecimal.ZERO;
        private BigDecimal refundAmount = BigDecimal.ZERO;
    }

    @Override
    public void statistic() {
        // 获取前一天
        DateTime yesterday = DateUtil.yesterday();
        // 获取前一天的开始时间（00:00:00）
        DateTime startOfDay = DateUtil.beginOfDay(yesterday);
        // 获取前一天的结束时间（23:59:59）
        DateTime endOfDay = DateUtil.endOfDay(yesterday);

        List<OrderDetail> orderDetails = orderDetailService.list(new QueryWrapper()
                .ge(OrderDetail::getCreateTime, startOfDay)
                .le(OrderDetail::getCreateTime, endOfDay)
                .ne(OrderDetail::getStatus, "wait-pay"));


        HashMap<Long, Map<Long, StatisticTask>> countInfo = new HashMap<>();
        for (OrderDetail item : orderDetails) {
            Map<Long, StatisticTask> map = countInfo.computeIfAbsent(item.getShopId(), k -> new HashMap<>());
            StatisticTask statisticTask = map.get(item.getProductId());
            if (statisticTask == null) {
                map.put(item.getProductId(), statisticTask = new StatisticTask());
            }
            if ("refunding".equals(item.getStatus()) || "refund".equals(item.getStatus()) || "part-refund".equals(item.getStatus())) {
                statisticTask.setRefundAmount(statisticTask.getRefundAmount().add(item.getReturnAmount()));
                statisticTask.setRefundCount(statisticTask.getRefundCount().add(item.getRefundNum()));
                if (item.getReturnNum().compareTo(item.getNum()) < 0) {
                    statisticTask.setSuccessAmount(statisticTask.getSuccessAmount().add(item.getPayAmount().subtract(item.getReturnAmount())));
                    statisticTask.setSuccessCount(statisticTask.getSuccessCount().add(item.getNum().subtract(item.getReturnAmount())));
                }
            }else {
                statisticTask.setSuccessCount(statisticTask.getSuccessCount().add(item.getNum()));
                statisticTask.setSuccessAmount(statisticTask.getSuccessAmount().add(item.getPayAmount()));
            }
        }

        countInfo.forEach((shopId, map) -> map.forEach((productId, statisticTask) -> {
            ShopProdStatistic statistic = getOne(new QueryWrapper().eq(ShopProdStatistic::getShopId, shopId).eq(ShopProdStatistic::getCreateDay, yesterday.toSqlDate()));
            if (statistic == null) {
                statistic = new ShopProdStatistic();
                statistic.setShopId(shopId);
                statistic.setCreateDay(yesterday.toSqlDate());
            }
            statistic.setProdId(productId);
            statistic.setSaleCount(statisticTask.getSuccessCount());
            statistic.setSaleAmount(statisticTask.getSuccessAmount());
            statistic.setRefundCount(statisticTask.getRefundCount());
            statistic.setRefundAmount(statisticTask.getRefundAmount());
            saveOrUpdate(statistic);
        }));


    }


}
