package com.test.musichouduan.service.impl;

import com.test.musichouduan.dto.MusicDTO;
import com.test.musichouduan.dto.MusicTypeDTO;
import com.test.musichouduan.dto.UserDTO;
import com.test.musichouduan.entity.Music;
import com.test.musichouduan.entity.MusicType;
import com.test.musichouduan.entity.User;
import com.test.musichouduan.repository.*;
import com.test.musichouduan.service.StatService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 统计服务实现类
 */
@Service
public class StatServiceImpl implements StatService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private MusicRepository musicRepository;

    @Autowired
    private PlaylistRepository playlistRepository;

    @Autowired
    private SingerRepository singerRepository;

    @Autowired
    private MusicTypeRepository musicTypeRepository;

    @Autowired
    private PlayHistoryRepository playHistoryRepository;

    @Override
    public Map<String, Object> getTotalStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("userCount", userRepository.count());
        stats.put("musicCount", musicRepository.count());
        stats.put("playlistCount", playlistRepository.count());
        stats.put("singerCount", singerRepository.count());

        // 计算总播放量
        long totalPlayCount = 0;
        List<Music> allMusic = musicRepository.findAll();
        for (Music music : allMusic) {
            totalPlayCount += music.getPlayCount() != null ? music.getPlayCount() : 0;
        }
        stats.put("playCount", totalPlayCount);

        return stats;
    }

    @Override
    public Map<String, Object> getUserGrowthTrend(Integer days) {
        Map<String, Object> stats = new HashMap<>();
        List<String> dateList = new ArrayList<>();
        List<Long> countList = new ArrayList<>();

        // 获取日期列表
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(days - 1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");

        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            dateList.add(date.format(formatter));

            // 计算当天注册用户数
            LocalDateTime start = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime end = LocalDateTime.of(date, LocalTime.MAX);
            long count = userRepository.countByCreateTimeBetween(start, end);
            countList.add(count);
        }

        stats.put("dates", dateList);
        stats.put("counts", countList);
        return stats;
    }

    @Override
    public Map<String, Object> getMusicTypeDistribution() {
        Map<String, Object> stats = new HashMap<>();
        List<String> nameList = new ArrayList<>();
        List<Long> countList = new ArrayList<>();

        // 获取所有音乐类型
        List<MusicType> types = musicTypeRepository.findAll();
        for (MusicType type : types) {
            nameList.add(type.getName());
            long count = musicRepository.countByTypesContaining(type);
            countList.add(count);
        }

        stats.put("names", nameList);
        stats.put("counts", countList);
        return stats;
    }

    @Override
    public Map<String, Object> getPlayCountStats(Integer days) {
        Map<String, Object> stats = new HashMap<>();
        List<String> dateList = new ArrayList<>();
        List<Long> countList = new ArrayList<>();

        // 获取日期列表
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(days - 1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");

        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            dateList.add(date.format(formatter));

            // 计算当天播放次数
            LocalDateTime start = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime end = LocalDateTime.of(date, LocalTime.MAX);
            long count = playHistoryRepository.countByPlayTimeBetween(start, end);
            countList.add(count);
        }

        stats.put("dates", dateList);
        stats.put("counts", countList);
        return stats;
    }

    @Override
    public Map<String, Object> getLatestUsers(Integer limit) {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取最新用户
        List<User> users = userRepository.findAll(
                PageRequest.of(0, limit, Sort.by(Sort.Direction.DESC, "createTime"))
        ).getContent();
        
        List<UserDTO> userDTOList = users.stream().map(user -> {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(user, userDTO);
            return userDTO;
        }).collect(Collectors.toList());
        
        stats.put("users", userDTOList);
        return stats;
    }

    @Override
    public Map<String, Object> getLatestMusics(Integer limit) {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取最新音乐
        List<Music> musics = musicRepository.findAll(
                PageRequest.of(0, limit, Sort.by(Sort.Direction.DESC, "createTime"))
        ).getContent();
        
        List<MusicDTO> musicDTOList = musics.stream().map(music -> {
            MusicDTO musicDTO = new MusicDTO();
            BeanUtils.copyProperties(music, musicDTO);
            return musicDTO;
        }).collect(Collectors.toList());
        
        stats.put("musics", musicDTOList);
        return stats;
    }
}
