package com.red.circle.other.test;

import com.mongodb.client.result.DeleteResult;
import com.red.circle.OtherServiceApplication;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import org.bson.types.Decimal128;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * 主播礼物测试类
 */
@SpringBootTest(classes = OtherServiceApplication.class)
@RunWith(SpringRunner.class)
public class AnchorGiftTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 统计指定发送人和接收人之间的目标总金额
     */
    @Test
    public void testQueryTargetAmountSum() {
        Long userId = null;  // 发送礼物的人，null表示查询所有发送人
        Long acceptUserId = 1996197707655929857L;  // 接收礼物的人
        
        BigDecimal totalTargetAmount = queryTargetAmountSum(userId, acceptUserId);
        
        System.out.println("发送人ID: " + (userId == null ? "全部" : userId));
        System.out.println("接收人ID: " + acceptUserId);
        System.out.println("目标总金额: " + totalTargetAmount);
    }

    /**
     * 查询指定发送人和接收人之间的目标总金额
     *
     * @param userId 发送礼物的人ID，null表示查询所有发送人
     * @param acceptUserId 接收礼物的人ID
     * @return 目标总金额
     */
    private BigDecimal queryTargetAmountSum(Long userId, Long acceptUserId) {
        List<AggregationOperation> operations = new ArrayList<>();
        
        // 1. 匹配发送人（如果userId不为null）
        if (userId != null) {
            operations.add(Aggregation.match(Criteria.where("userId").is(userId)));
        }
        
        // 2. 展开 acceptUsers 数组
        operations.add(Aggregation.unwind("acceptUsers"));
        
        // 3. 匹配接收人
        operations.add(Aggregation.match(Criteria.where("acceptUsers.acceptUserId").is(acceptUserId)));
        
        // 4. 聚合求和
        operations.add(Aggregation.group().sum("acceptUsers.targetAmount").as("totalTargetAmount"));
        
        // 构建聚合查询
        Aggregation aggregation = Aggregation.newAggregation(operations);

        // 执行聚合查询
        AggregationResults<Document> results = mongoTemplate.aggregate(
                aggregation,
                "gift_give_running_water",
                Document.class
        );

        // 获取结果
        Document result = results.getUniqueMappedResult();
        if (result == null || result.get("totalTargetAmount") == null) {
            return BigDecimal.ZERO;
        }

        // MongoDB 中的 Decimal128 需要转换为 BigDecimal
        Object totalAmount = result.get("totalTargetAmount");
        if (totalAmount instanceof Decimal128) {
            return ((Decimal128) totalAmount).bigDecimalValue();
        } else if (totalAmount instanceof BigDecimal) {
            return (BigDecimal) totalAmount;
        } else if (totalAmount instanceof Number) {
            return new BigDecimal(totalAmount.toString());
        }
        
        return BigDecimal.ZERO;
    }

    /**
     * 按礼物ID分组统计详细信息
     */
    @Test
    public void testQueryGiftDetailGroupByGiftId() {
        Long userId = null;  // 发送礼物的人，null表示查询所有发送人
        Long acceptUserId = 1986355914717921281L;  // 接收礼物的人

        // 使用 UTC 时区
        LocalDateTime startOfDay = LocalDateTime.of(LocalDate.now(ZoneId.of("UTC")), LocalTime.MIN).minusDays(1);
        LocalDateTime endOfDay = LocalDateTime.of(LocalDate.now(ZoneId.of("UTC")), LocalTime.MAX).minusDays(1);

        List<GiftStatisticResult> results = queryGiftDetailGroupByGiftId(userId, acceptUserId, startOfDay, endOfDay);
        
        System.out.println("发送人ID: " + (userId == null ? "全部" : userId));
        System.out.println("接收人ID: " + acceptUserId);
        System.out.println("礼物统计结果:");
        System.out.println("========================================");
        
        for (GiftStatisticResult result : results) {
            System.out.println("礼物ID: " + result.getGiftId());
            System.out.println("礼物类型: " + result.getGiftType());
            System.out.println("是否幸运礼物: " + (result.getLuckyGift() ? "是" : "否"));
            System.out.println("赠送次数: " + result.getTotalCount());
            System.out.println("总数量: " + result.getTotalQuantity());
            System.out.println("总价值: " + result.getTotalGiftValue());
            System.out.println("总目标金额: " + result.getTotalTargetAmount());
            System.out.println("----------------------------------------");
        }
    }

    /**
     * 按礼物ID分组统计详细信息
     *
     * @param userId 发送礼物的人ID，null表示查询所有发送人
     * @param acceptUserId 接收礼物的人ID
     * @return 礼物统计结果列表
     */
    private List<GiftStatisticResult> queryGiftDetailGroupByGiftId(Long userId, Long acceptUserId, LocalDateTime startTime, LocalDateTime endTime) {
        List<AggregationOperation> operations = new ArrayList<>();

        // 1. 构建时间范围条件
        Criteria criteria = new Criteria();
        if (userId != null) {
            criteria.and("userId").is(userId);
        }
        if (startTime != null && endTime != null) {
            criteria.and("createTime").gte(startTime).lte(endTime);
        } else if (startTime != null) {
            criteria.and("createTime").gte(startTime);
        } else if (endTime != null) {
            criteria.and("createTime").lte(endTime);
        }

        if (!criteria.getCriteriaObject().isEmpty()) {
            operations.add(Aggregation.match(criteria));
        }

        // 2. 展开 acceptUsers 数组
        operations.add(Aggregation.unwind("acceptUsers"));


        // 3. 匹配接收人
        operations.add(Aggregation.match(Criteria.where("acceptUsers.acceptUserId").is(acceptUserId)));
        
        // 4. 按礼物ID分组并统计
        operations.add(Aggregation.group("giftId")
                .first("giftId").as("giftId")
                .first("giftType").as("giftType")
                .first("luckyGift").as("luckyGift")
                .count().as("totalCount")  // 赠送次数
                .sum("giftValue.quantity").as("totalQuantity")  // 总数量
                .sum("giftValue.giftValue").as("totalGiftValue")  // 总价值
                .sum("acceptUsers.targetAmount").as("totalTargetAmount")  // 总目标金额
        );
        
        // 5. 按总目标金额降序排序
        operations.add(Aggregation.sort(org.springframework.data.domain.Sort.Direction.DESC, "totalTargetAmount"));
        
        // 构建聚合查询
        Aggregation aggregation = Aggregation.newAggregation(operations);

        // 执行聚合查询
        AggregationResults<Document> results = mongoTemplate.aggregate(
                aggregation,
                "gift_give_running_water",
                Document.class
        );

        // 转换结果
        List<GiftStatisticResult> resultList = new ArrayList<>();
        for (Document doc : results.getMappedResults()) {
            GiftStatisticResult result = new GiftStatisticResult();
            result.setGiftId(doc.getLong("giftId"));
            result.setGiftType(doc.getString("giftType"));
            result.setLuckyGift(doc.getBoolean("luckyGift", false));
            result.setTotalCount(doc.getInteger("totalCount", 0));
            result.setTotalQuantity(doc.getInteger("totalQuantity", 0));
            result.setTotalGiftValue(convertToBigDecimal(doc.get("totalGiftValue")));
            result.setTotalTargetAmount(convertToBigDecimal(doc.get("totalTargetAmount")));
            resultList.add(result);
        }
        
        return resultList;
    }

    /**
     * 将MongoDB的数字类型转换为BigDecimal
     */
    private BigDecimal convertToBigDecimal(Object value) {
        if (value == null) {
            return BigDecimal.ZERO;
        }
        if (value instanceof Decimal128) {
            return ((Decimal128) value).bigDecimalValue();
        } else if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        } else if (value instanceof Number) {
            return new BigDecimal(value.toString());
        }
        return BigDecimal.ZERO;
    }

    /**
     * 礼物统计结果
     */
    public static class GiftStatisticResult {
        private Long giftId;
        private String giftType;
        private Boolean luckyGift;
        private Integer totalCount;
        private Integer totalQuantity;
        private BigDecimal totalGiftValue;
        private BigDecimal totalTargetAmount;

        public Long getGiftId() {
            return giftId;
        }

        public void setGiftId(Long giftId) {
            this.giftId = giftId;
        }

        public String getGiftType() {
            return giftType;
        }

        public void setGiftType(String giftType) {
            this.giftType = giftType;
        }

        public Boolean getLuckyGift() {
            return luckyGift;
        }

        public void setLuckyGift(Boolean luckyGift) {
            this.luckyGift = luckyGift;
        }

        public Integer getTotalCount() {
            return totalCount;
        }

        public void setTotalCount(Integer totalCount) {
            this.totalCount = totalCount;
        }

        public Integer getTotalQuantity() {
            return totalQuantity;
        }

        public void setTotalQuantity(Integer totalQuantity) {
            this.totalQuantity = totalQuantity;
        }

        public BigDecimal getTotalGiftValue() {
            return totalGiftValue;
        }

        public void setTotalGiftValue(BigDecimal totalGiftValue) {
            this.totalGiftValue = totalGiftValue;
        }

        public BigDecimal getTotalTargetAmount() {
            return totalTargetAmount;
        }

        public void setTotalTargetAmount(BigDecimal totalTargetAmount) {
            this.totalTargetAmount = totalTargetAmount;
        }
    }

}