package cn.reghao.tnb.content.app.vod.service;

import cn.reghao.jutil.jdk.converter.DateTimeConverter;
import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.content.app.vod.model.po.VideoCategory;
import cn.reghao.tnb.content.app.vod.model.query.CategoryQuery;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2023-10-11 14:35:46
 */
@Service
public class WatchAnalysisService {
    private final CategoryService categoryService;

    public WatchAnalysisService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    public List<String> getLineChartData() {
        long loginUser = UserContext.getUser();

        List<String> xAxis = new ArrayList<>();
        LocalDateTime current = LocalDateTime.now();
        int i = 8;
        while (i-- > 1) {
            LocalDateTime localDateTime = current.minusDays(i);
            String dtStr = DateTimeConverter.format(localDateTime);
            xAxis.add(dtStr.split(" ")[0]);
        }
        String xStr = xAxis.toString().replace("[", "").replace("]", "");

        List<String> yAxis = new ArrayList<>();
        for (int j = 0; j < 7; j++) {
            yAxis.add(String.format("%.2f", getRandomDouble()));
        }
        String yStr = yAxis.toString().replace("[", "").replace("]", "");

        List<String> list = new ArrayList<>();
        list.add(xStr);
        list.add(yStr);
        return list;
    }

    public List<String> getPieChartData() {
        long loginUser = UserContext.getUser();

        CategoryQuery categoryQuery = new CategoryQuery.Builder().pid(1).build();
        List<VideoCategory> videoCategories = categoryService.getVideoCategories(categoryQuery);
        List<String> names = videoCategories.stream().map(VideoCategory::getName).collect(Collectors.toList());
        int total = names.size();
        List<String> xAxis = new ArrayList<>();
        int i = 8;
        while (i-- > 1) {
            xAxis.add(names.get(getRandomInt(total)));
        }
        String xStr = xAxis.toString().replace("[", "").replace("]", "");

        List<String> yAxis = new ArrayList<>();
        for (int j = 0; j < 7; j++) {
            yAxis.add(String.valueOf(getRandomInt(100)));
        }
        String yStr = yAxis.toString().replace("[", "").replace("]", "");

        List<String> list = new ArrayList<>();
        list.add(xStr);
        list.add(yStr);
        return list;
    }

    Random random = new SecureRandom();
    private double getRandomDouble() {
        int max = 86400;
        double randomNum = getRandomInt(max);
        return randomNum/3600;
    }

    private int getRandomInt(int max) {
        int min = 0;
        return min + random.nextInt(max - min);
    }
}
