package com.red.circle.other.infra.gateway;

import com.red.circle.other.domain.ranking.RankingActivityType;
import com.red.circle.other.domain.ranking.RankingCycleType;
import com.red.circle.other.infra.database.mongo.entity.activity.RankingActivityRecord;
import com.red.circle.other.infra.database.mongo.service.activity.RankingActivityRecordRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Component;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;

/**
 * 排行榜活动领域网关实现
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RankingActivityGatewayImpl implements RankingActivityGateway {

    private final RankingActivityRecordRepository repository;
    private final MongoTemplate mongoTemplate;

    private static final Integer NOT_DELETED = 0;

    @Override
    public RankingActivityRecord accumulateRankingData(RankingActivityRecord record, Long incrementQuantity) {
        Timestamp now = new Timestamp(System.currentTimeMillis());

        // 构建查询条件：根据业务唯一键
        Query query = new Query(Criteria
                .where("sysOrigin").is(record.getSysOrigin())
                .and("userId").is(record.getUserId())
                .and("activityType").is(record.getActivityType())
                .and("cycleKey").is(record.getCycleKey())
                .and("deleted").is(NOT_DELETED)
        );

        // 构建更新操作
        Update update = new Update()
                .inc("quantity", incrementQuantity)
                .set("updateTime", now)

                .setOnInsert("sysOrigin", record.getSysOrigin())
                .setOnInsert("userId", record.getUserId())
                .setOnInsert("userSex", record.getUserSex())
                .setOnInsert("activityType", record.getActivityType())
                .setOnInsert("cycleType", record.getCycleType())
                .setOnInsert("cycleKey", record.getCycleKey())
                .setOnInsert("dimension", record.getDimension())
                .setOnInsert("extData", record.getExtData())
                .setOnInsert("expiredTime", record.getExpiredTime())
                .setOnInsert("createTime", now)
                .setOnInsert("deleted", NOT_DELETED);

        FindAndModifyOptions options = new FindAndModifyOptions()
                .upsert(true)       // 不存在则插入
                .returnNew(true);   // 返回更新后的文档
        return mongoTemplate.findAndModify(query, update, options, RankingActivityRecord.class);
    }

    @Override
    public Optional<RankingActivityRecord> getUserRecord(
            String sysOrigin,
            Long userId,
            RankingActivityType activityType,
            String cycleKey) {
        return repository.findBySysOriginAndUserIdAndActivityTypeAndCycleKeyAndDeleted(
                sysOrigin, userId, activityType, cycleKey, NOT_DELETED
        );
    }

    @Override
    public List<RankingActivityRecord> getRankingList(
            String sysOrigin,
            RankingActivityType activityType,
            RankingCycleType cycleType,
            String cycleKey,
            Integer userSex,
            Integer topN) {
        
        PageRequest pageRequest = PageRequest.of(0, topN);
        
        if (userSex == null) {
            // 不限性别
            return repository.findBySysOriginAndActivityTypeAndCycleTypeAndCycleKeyAndDeletedOrderByQuantityDescCreateTimeAsc(
                    sysOrigin, activityType, cycleType, cycleKey, NOT_DELETED, pageRequest
            );
        } else {
            // 按性别筛选
            return repository.findBySysOriginAndActivityTypeAndCycleTypeAndCycleKeyAndUserSexAndDeletedOrderByQuantityDescCreateTimeAsc(
                    sysOrigin, activityType, cycleType, cycleKey, userSex, NOT_DELETED, pageRequest
            );
        }
    }

    @Override
    public Integer calculateUserRank(
            String sysOrigin,
            RankingActivityType activityType,
            RankingCycleType cycleType,
            String cycleKey,
            Integer userSex,
            Long quantity) {
        
        Long countGreater;
        
        if (userSex == null) {
            // 不限性别
            countGreater = repository.countByQuantityGreaterThanWithoutSex(
                    sysOrigin, activityType, cycleType, cycleKey, NOT_DELETED, quantity
            );
        } else {
            // 按性别筛选
            countGreater = repository.countByQuantityGreaterThan(
                    sysOrigin, activityType, cycleType, cycleKey, userSex, NOT_DELETED, quantity
            );
        }
        
        // 排名 = 比我多的人数 + 1
        return Math.toIntExact((countGreater == null ? 0 : countGreater) + 1);
    }

    @Override
    public Long countTotalParticipants(
            String sysOrigin,
            RankingActivityType activityType,
            RankingCycleType cycleType,
            String cycleKey,
            Integer userSex) {
        
        if (userSex == null) {
            // 不限性别
            return repository.countBySysOriginAndActivityTypeAndCycleTypeAndCycleKeyAndDeleted(
                    sysOrigin, activityType, cycleType, cycleKey, NOT_DELETED
            );
        } else {
            // 按性别筛选
            return repository.countBySysOriginAndActivityTypeAndCycleTypeAndCycleKeyAndUserSexAndDeleted(
                    sysOrigin, activityType, cycleType, cycleKey, userSex, NOT_DELETED
            );
        }
    }

    @Override
    public RankingActivityRecord save(RankingActivityRecord record) {
        return repository.save(record);
    }

    @Override
    public List<RankingActivityRecord> batchGetUserRecords(
            List<Long> userIds,
            RankingActivityType activityType,
            String cycleKey) {
        return repository.findByUserIdInAndActivityTypeAndCycleKeyAndDeleted(
                userIds, activityType, cycleKey, NOT_DELETED
        );
    }

    @Override
    public List<RankingActivityRecord> getOverallRankingList(
            String sysOrigin,
            RankingActivityType activityType,
            Integer topN) {
        
        // 使用 MongoDB 聚合查询，按 userId 分组汇总所有周期的数据
        Aggregation aggregation =
            Aggregation.newAggregation(
                // 1. 匹配条件：平台、活动类型、未删除
                Aggregation.match(
                    Criteria.where("sysOrigin").is(sysOrigin)
                        .and("activityType").is(activityType)
                        .and("deleted").is(NOT_DELETED)
                ),
                // 2. 按 userId 分组，汇总 quantity
                Aggregation.group("userId")
                    .sum("quantity").as("quantity")
                    .first("userId").as("userId")
                    .first("userSex").as("userSex")
                    .first("activityType").as("activityType")
                    .first("dimension").as("dimension")
                    .first("createTime").as("createTime"),
                // 3. 按总数量降序排序，createTime升序排序
                Aggregation.sort(
                        org.springframework.data.domain.Sort.Direction.DESC, "quantity"
                ).and(
                        org.springframework.data.domain.Sort.Direction.ASC, "createTime"
                ),
                // 4. 限制返回数量
                Aggregation.limit(topN)
            );
        
        // 执行聚合查询
        List<RankingActivityRecord> results = mongoTemplate.aggregate(
            aggregation,
            "ranking_activity_record",  // collection name
            RankingActivityRecord.class
        ).getMappedResults();
        
        return results;
    }
}
