package org.jeecg.modules.adweb.dmp.controller;

import static org.jeecg.modules.adweb.dmp.vo.report.SiteOverviewStatsVO.DailyStatsVO;

import io.swagger.v3.oas.annotations.tags.Tag;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.adweb.common.util.DateUtil;
import org.jeecg.modules.adweb.dmp.service.*;
import org.jeecg.modules.adweb.dmp.vo.report.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 数据分析 - GA网站流量，询盘数据等
 *
 * @author wfansh
 */
@Tag(name = "DMP数据分析 - 网站流量，询盘数据等")
@RestController
@RequestMapping("/dmp-data")
@Slf4j
public class DMPDataController {

    @Value("${v3.dmp.realtimeReport}")
    private boolean realtimeReport; // 实时报表开关，true-从DataBridge实时读取 false-从DB离线读取

    @Autowired private IGADailyReportService gaDailyReportService;
    @Autowired private IGACountryReportService gaCountryReportService;
    @Autowired private IGASourceMediumReportService gaSourceMediumReportService;
    @Autowired private IGAPagePathReportService gaPagePathReportService;
    @Autowired private IGADeviceReportService gaDeviceReportService;
    @Autowired private IEnquiryReportService enquiryReportService;
    @Autowired private RealtimeReportService realtimeReportService;

    /** 首页：网站流量按时间段分析统计 - 今天，昨天，本周，上周等 */
    @GetMapping("/site-periodic/stats")
    public Result<Map<String, PeriodicStatsVO>> getSitePeriodicStats(String siteCode) {
        // 1. 查询分时间段的GA Report和Enquiries
        List<PeriodicStatsVO> periodicStatsVOs =
                realtimeReport
                        ? realtimeReportService.getPeriodicStats(siteCode)
                        : gaDailyReportService.getPeriodicStats(siteCode);

        // 2. 转换为Map并返回
        return Result.ok(
                periodicStatsVOs.stream()
                        .collect(
                                Collectors.toMap(PeriodicStatsVO::getPeriod, Function.identity())));
    }

    /** 网站流量整体分析统计 */
    @GetMapping("/site-overview/stats")
    public Result<SiteOverviewStatsVO> getSiteOverviewStats(
            String siteCode,
            String dateType,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date start,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date end) {
        // 1. 计算时间区间
        if (StringUtils.isNotBlank(dateType)) {
            Pair<Date, Date> dateRange = DateUtil.getDateRangeByType(dateType);
            start = dateRange.getLeft();
            end = dateRange.getRight();
        }

        // 2. TODO: 实时或DB离线查询
        List<DailyStatsVO> dailyStatsVOs =
                realtimeReport
                        ? realtimeReportService.getDailyStats(siteCode, start, end)
                        : gaDailyReportService.getDailyStats(siteCode, start, end);

        // 3. 生成SiteOverviewStatsVO并返回
        return Result.ok(SiteOverviewStatsVO.fromDailyStats(dailyStatsVOs));
    }

    @GetMapping("/country/stats")
    public Result<List<CountryStatsVO>> getCountryStats(
            String siteCode,
            String dateType,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date start,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date end) {
        // 1. 计算时间区间
        if (StringUtils.isNotBlank(dateType)) {
            Pair<Date, Date> dateRange = DateUtil.getDateRangeByType(dateType);
            start = dateRange.getLeft();
            end = dateRange.getRight();
        }

        // 2. TODO: 实时或DB离线查询
        List<CountryStatsVO> countryStatsVOs =
                realtimeReport
                        ? realtimeReportService.getCountryStats(siteCode, start, end)
                        : gaCountryReportService.getCountryStats(siteCode, start, end);
        return Result.ok(countryStatsVOs);
    }

    @GetMapping("/source-medium/stats")
    public Result<List<SourceMediumStatsVO>> getSourceMediumStats(
            String siteCode,
            String dateType,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date start,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date end) {
        // 1. 计算时间区间
        if (StringUtils.isNotBlank(dateType)) {
            Pair<Date, Date> dateRange = DateUtil.getDateRangeByType(dateType);
            start = dateRange.getLeft();
            end = dateRange.getRight();
        }

        // 2. TODO: 实时或DB离线查询
        List<SourceMediumStatsVO> sourceMediumStatsVOs =
                realtimeReport
                        ? realtimeReportService.getSourceMediumStats(siteCode, start, end)
                        : gaSourceMediumReportService.getSourceMediumStats(siteCode, start, end);
        return Result.ok(sourceMediumStatsVOs);
    }

    @GetMapping("/page-path/stats")
    public Result<List<PagePathStatsVO>> getPagePathStats(
            String siteCode,
            String dateType,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date start,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date end,
            int limit) {
        // 1. 计算时间区间
        if (StringUtils.isNotBlank(dateType)) {
            Pair<Date, Date> dateRange = DateUtil.getDateRangeByType(dateType);
            start = dateRange.getLeft();
            end = dateRange.getRight();
        }

        // 2. TODO: 实时或DB离线查询
        limit = limit >= 0 ? limit : 10;
        List<PagePathStatsVO> pagePathStatsVOs =
                realtimeReport
                        ? realtimeReportService.getPagePathStats(siteCode, start, end, limit)
                        : gaPagePathReportService.getPagePathStats(siteCode, start, end, limit);
        return Result.ok(pagePathStatsVOs);
    }

    @GetMapping("/device/stats")
    public Result<List<DeviceStatsVO>> getDeviceStats(
            String siteCode,
            String dateType,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date start,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date end) {
        // 1. 计算时间区间
        if (StringUtils.isNotBlank(dateType)) {
            Pair<Date, Date> dateRange = DateUtil.getDateRangeByType(dateType);
            start = dateRange.getLeft();
            end = dateRange.getRight();
        }

        // 2. TODO: 实时或DB离线查询
        List<DeviceStatsVO> deviceStatsVOs =
                realtimeReport
                        ? realtimeReportService.getDeviceStats(siteCode, start, end)
                        : gaDeviceReportService.getDeviceStats(siteCode, start, end);
        return Result.ok(deviceStatsVOs);
    }

    @GetMapping("/enquiry-country/stats")
    public Result<List<EnquiryCountryStatsVO>> getEnquiryCountryStats(
            String siteCode,
            String dateType,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date start,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date end) {
        // 1. 计算时间区间
        if (StringUtils.isNotBlank(dateType)) {
            Pair<Date, Date> dateRange = DateUtil.getDateRangeByType(dateType);
            start = dateRange.getLeft();
            end = dateRange.getRight();
        }

        // 2. 查询并返回
        return Result.ok(enquiryReportService.getEnquiryCountryStats(siteCode, start, end));
    }
}
