package com.backendsys.service.Ai.Aiivh;

import com.backendsys.aspect.HttpRequestAspect;
import com.backendsys.entity.Ai.Aiivh.AiivhAsset.AiivhAssetQuotaStatisticsDTO;
import com.backendsys.entity.Ai.Aiivh.AiivhAsset.QuotaStatistics;
import com.backendsys.entity.Ai.Aiivh.AiivhQuotaDTO;
import com.backendsys.mapper.Ai.Aiivh.AiivhQuotaMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AiivhAssetServiceImpl implements AiivhAssetService{

    @Autowired
    private HttpRequestAspect httpRequestAspect;

    @Autowired
    private AiivhQuotaMapper aiivhQuotaMapper;


    // 判断给定的日期是否过期
//    boolean isExpired(String expireDateStr) {
//        // 将字符串转换为 LocalDate 对象
//        LocalDate expireDate = LocalDate.parse(expireDateStr);
//        // 获取当前日期
//        LocalDate currentDate = LocalDate.now();
//        // 比较日期，判断是否过期
//        return currentDate.isAfter(expireDate);
//    }
    boolean isExpired(String dateTimeStr) {
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 使用 LocalDateTime 解析日期时间字符串
        LocalDateTime expireDateTime = LocalDateTime.parse(dateTimeStr, formatter);
        // 获取当前的 LocalDateTime
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 比较日期时间，判断是否过期
        return currentDateTime.isAfter(expireDateTime);
    }
    private static QuotaStatistics getCounts(Map<String, Map<Boolean, Long>> statusCounts) {
        return new QuotaStatistics(
            statusCounts.getOrDefault("1", Map.of(false, 0L, true, 0L)),
            statusCounts.getOrDefault("2", Map.of(false, 0L, true, 0L)),
            statusCounts.getOrDefault("3", Map.of(false, 0L, true, 0L))
        );
    }

    /**
     * 我的数智人资产一览
     * {
     * 	"anchor_free_quota": 2,
     * 	"anchor_used_quota": 0,
     * 	"anchor_expire_quota": 2,
     * 	"anchor_count": 0,
     * 	"timbre_free_quota": 2,
     * 	"timbre_used_quota": 1,
     * 	"timbre_expire_quota": 0,
     * 	"timbre_count": 1,
     * 	"broadcast_count": 0,
     * 	"broadcast_audio_count": 0
     * }
     */
    @Override
    public AiivhAssetQuotaStatisticsDTO getMyOverview() {

        // 可定制
        AiivhQuotaDTO aiivhQuotaDTO = new AiivhQuotaDTO();
        aiivhQuotaDTO.setUser_id(httpRequestAspect.getUserId());
        List<Map<String, Object>> resp = aiivhQuotaMapper.queryAiivhQuotaList(aiivhQuotaDTO);
        // System.out.println(resp);


        // -- 根据 quota_type、quota_status 和 expire_date 是否过期分组并计数 ---------------------------------
        Map<String, Map<String, Map<Boolean, Long>>> quotaGroupCount = resp.stream()
            .collect(Collectors.groupingBy(
                item -> (String) item.get("quota_type"), // 外层分组依据 "quota_type"
                Collectors.groupingBy(
                    item -> String.valueOf((Integer) item.get("quota_status")), // 中层分组依据 "quota_status"
                    Collectors.groupingBy(
                        item -> isExpired((String) item.get("expire_date")), // 内层分组依据是否过期
                        Collectors.counting() // 计数
                    )
                )
            ));

//        System.out.println(quotaGroupCount);

        // {Anchor={1={false=2, true=1}, 2={true=1}}, Timbre={1={false=2}, 2={false=1}, 3={false=1}}}
        // quotaGroupCount 的结构将是：quota_type -> quota_status -> (expire_date 是否过期 false) -> 相关记录的数量
        // -----------------------------------------------------------------------------------------------

        // -- 为每个 quota_type 获取统计信息 (实例化，方便获取统计) ---------------------------------------------
        Map<String, QuotaStatistics> statistics = quotaGroupCount.entrySet().stream()
            .collect(Collectors.toMap(
                Map.Entry::getKey,
                entry -> getCounts(entry.getValue())
            ));

//        System.out.println(statistics);

        // {Anchor=QuotaStatistics(free={false=2, true=1}, using={true=1}, used={false=0, true=0}), Timbre=QuotaStatistics(free={false=2}, using={false=1}, used={false=1})}
        // -----------------------------------------------------------------------------------------------

        // -- 将分组归类 -----------------------------------------------------------------------------------
        AiivhAssetQuotaStatisticsDTO aiivhAssetQuotaStatisticsDTO = new AiivhAssetQuotaStatisticsDTO();
        aiivhAssetQuotaStatisticsDTO.setDefaultZero();

        statistics.forEach((quotaType, result) -> {
//            System.out.println("Quota Type: " + quotaType);
//            System.out.println("Free Unexpired: " + result.getFreeUnexpired() + " , " + "Free Expired: " + result.getFreeExpired());
//            System.out.println("Using Unexpired: " + result.getUsingUnexpired() + " , " + "Using Expired: " + result.getUsingExpired());
//            System.out.println("Used Unexpired: " + result.getUsedUnexpired() + " , " + "Used Expired: " + result.getUsedExpired());
            if (quotaType.equals("Anchor")) {
                aiivhAssetQuotaStatisticsDTO.setAnchor_free_quota(result.getFreeUnexpired());   // 形象 未使用
                aiivhAssetQuotaStatisticsDTO.setAnchor_using_count(result.getUsingUnexpired());       // 形象 使用中
                aiivhAssetQuotaStatisticsDTO.setAnchor_used_quota(result.getUsedUnexpired());   // 形象 已使用
                // 过期形象 (未使用 + 使用中 + 已使用) 数量
                aiivhAssetQuotaStatisticsDTO.setAnchor_expire_quota(result.getFreeExpired() + result.getUsingExpired() + result.getUsedExpired());
            }
            if (quotaType.equals("Timbre")) {
                aiivhAssetQuotaStatisticsDTO.setTimbre_free_quota(result.getFreeUnexpired());   // 形象 未使用
                aiivhAssetQuotaStatisticsDTO.setTimbre_using_count(result.getUsingUnexpired());       // 形象 使用中
                aiivhAssetQuotaStatisticsDTO.setTimbre_used_quota(result.getUsedUnexpired());   // 形象 已使用
                // 过期形象 (未使用 + 使用中 + 已使用) 数量
                aiivhAssetQuotaStatisticsDTO.setTimbre_expire_quota(result.getFreeExpired() + result.getUsingExpired() + result.getUsedExpired());
            }
        });
        // ----------------------------------------------------------------------------------------------



//        // 播报统计 (待定) (这里获得的是已经生成过的视频或音频播报的分钟) (生成音频还没做，所以暂时不做)
//        aiivhAssetQuotaStatisticsDTO.setBroadcast_count(0L);
//        aiivhAssetQuotaStatisticsDTO.setBroadcast_audio_count(0L);

        return aiivhAssetQuotaStatisticsDTO;

    }





}
