package com.haha.service.impl;

import com.haha.common.enums.UserTag;
import com.haha.mapper.OrderMapper;
import com.haha.service.UserTagService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 用户消费标签服务实现
 * 通过批量SQL预计算用户消费数据，在内存中映射标签
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserTagServiceImpl implements UserTagService {

    private final OrderMapper orderMapper;

    /** 常客判定阈值：近30天消费次数 >= 此值 */
    private static final int FREQUENT_THRESHOLD = 4;
    /** 老用户判定阈值：总消费次数 >= 此值 */
    private static final int REGULAR_THRESHOLD = 2;

    @Override
    public Map<Long, UserTag> batchComputeUserTags(List<Long> userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return Collections.emptyMap();
        }

        // 去重
        List<Long> distinctUserIds = userIds.stream().distinct().toList();

        // 1. 批量查询总消费次数（已支付订单）
        List<Map<String, Object>> totalCounts = orderMapper.batchCountPaidOrdersByUserIds(distinctUserIds);
        Map<Long, Integer> totalCountMap = new HashMap<>();
        for (Map<String, Object> row : totalCounts) {
            Long userId = ((Number) row.get("user_id")).longValue();
            int count = ((Number) row.get("order_count")).intValue();
            totalCountMap.put(userId, count);
        }

        // 2. 批量查询近30天消费次数（已支付订单）
        LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);
        List<Map<String, Object>> recentCounts = orderMapper.batchCountRecentPaidOrdersByUserIds(distinctUserIds, thirtyDaysAgo);
        Map<Long, Integer> recentCountMap = new HashMap<>();
        for (Map<String, Object> row : recentCounts) {
            Long userId = ((Number) row.get("user_id")).longValue();
            int count = ((Number) row.get("order_count")).intValue();
            recentCountMap.put(userId, count);
        }

        // 3. 批量查询总订单数（包含所有状态，用于判断"新用户"）
        List<Map<String, Object>> allOrderCounts = orderMapper.batchCountAllOrdersByUserIds(distinctUserIds);
        Map<Long, Integer> allOrderCountMap = new HashMap<>();
        for (Map<String, Object> row : allOrderCounts) {
            Long userId = ((Number) row.get("user_id")).longValue();
            int count = ((Number) row.get("order_count")).intValue();
            allOrderCountMap.put(userId, count);
        }

        // 4. 按优先级判断标签：常客 > 老用户 > 新用户 > 潜在用户
        Map<Long, UserTag> result = new HashMap<>();
        for (Long userId : distinctUserIds) {
            int paidTotalCount = totalCountMap.getOrDefault(userId, 0);
            int paidRecentCount = recentCountMap.getOrDefault(userId, 0);
            int allOrderCount = allOrderCountMap.getOrDefault(userId, 0);

            UserTag tag;
            if (paidRecentCount >= FREQUENT_THRESHOLD) {
                tag = UserTag.FREQUENT;
            } else if (paidTotalCount >= REGULAR_THRESHOLD) {
                tag = UserTag.REGULAR;
            } else if (paidTotalCount == 1) {
                tag = UserTag.NEW;
            } else if (allOrderCount >= 1) {
                // 有下单行为但尚未完成支付的用户
                tag = UserTag.POTENTIAL;
            } else {
                // 完全没有订单记录的用户，不设置标签
                continue;
            }
            result.put(userId, tag);
        }

        log.debug("批量计算用户标签完成：输入{}个用户，输出{}个标签", distinctUserIds.size(), result.size());
        return result;
    }
}
