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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.czg.order.entity.ShopProdStatistic;
import com.czg.order.param.DataSummaryProductSaleParam;
import com.czg.order.service.DataSummaryService;
import com.czg.order.service.ShopProdStatisticService;
import com.czg.order.vo.DataSummaryProductSaleRankingVo;
import com.czg.service.order.mapper.ShopProdStatisticMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * 服务层实现。
 *
 * @author zs
 * @since 2025-03-07
 */
@Service
@Slf4j
public class ShopProdStatisticServiceImpl extends ServiceImpl<ShopProdStatisticMapper, ShopProdStatistic> implements ShopProdStatisticService {
    @Resource
    private DataSummaryService dataSummaryService;
    @Resource
    private ShopProdStatisticMapper shopProdStatisticMapper;

    @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 dateTime) {
        // 获取前一天的开始时间（00:00:00）
        DateTime startOfDay = DateUtil.beginOfDay(dateTime);
        // 获取前一天的结束时间（23:59:59）
        DateTime endOfDay = DateUtil.endOfDay(dateTime);
        List<Long> shopIdList = dataSummaryService.getShopIdList();
        if (CollUtil.isEmpty(shopIdList)) {
            return;
        }
        List<List<Long>> split = CollUtil.split(shopIdList, 5);
        for (List<Long> splitIdList : split) {
            splitIdList.parallelStream().forEach(shopId -> {
                DataSummaryProductSaleParam param = new DataSummaryProductSaleParam();
                param.setShopId(shopId);
                param.setBeginDate(startOfDay.toStringDefaultTimeZone());
                param.setEndDate(endOfDay.toStringDefaultTimeZone());
                // 删除之前统计数据
                getMapper().deleteByQuery(
                        QueryWrapper.create()
                                .eq("shop_id", shopId)
                                .eq("create_day", dateTime.toDateStr()));
                // 重新统计数据
                List<DataSummaryProductSaleRankingVo> list = shopProdStatisticMapper.findProdRandingSummaryPage2(param);
                for (DataSummaryProductSaleRankingVo dto : list) {
                    ShopProdStatistic entity = new ShopProdStatistic();
                    entity.setProdId(dto.getProductId());
                    entity.setSaleCount(dto.getNumber());
                    entity.setSaleAmount(dto.getAmount());
                    entity.setRefundCount(dto.getRefundCount());
                    entity.setRefundAmount(dto.getRefundAmount());
                    entity.setShopId(shopId);
                    entity.setCreateDay(dateTime.toJdkDate());
                    if (NumberUtil.isLessOrEqual(entity.getSaleCount(), BigDecimal.ZERO) && NumberUtil.isLessOrEqual(entity.getRefundCount(), BigDecimal.ZERO)) {
                        log.info("店铺：{}，{}，没有要存档的商品统计数据", shopId, dateTime.toDateStr());
                    } else {
                        save(entity);
                    }
                }
            });
        }
    }
}
