package com.yushu.web.controller.system;

import com.yushu.common.core.controller.BaseController;
import com.yushu.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 系统统计数据接口
 * 
 * @author yushu
 */
@RestController
@RequestMapping("/system/statistics")
public class SysStatisticsController extends BaseController
{
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 获取首页统计数据
     */
    @GetMapping("/dashboard")
    public AjaxResult getDashboardStats()
    {
        Map<String, Object> stats = new HashMap<>();
        
        // 用户总数
        Integer userCount = jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM sys_user WHERE del_flag = '0'", Integer.class);
        stats.put("userCount", userCount != null ? userCount : 0);
        
        // 消息数量（对话消息 + 系统通知）
        Integer messageCount = 0;
        try {
            Integer chatCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_chat_message", Integer.class);
            Integer notifyCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_notification", Integer.class);
            messageCount = (chatCount != null ? chatCount : 0) + (notifyCount != null ? notifyCount : 0);
        } catch (Exception e) {
            // 表可能不存在
            messageCount = 0;
        }
        stats.put("messageCount", messageCount);
        
        // 文件数量
        Integer fileCount = 0;
        try {
            fileCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_file WHERE del_flag = '0'", Integer.class);
        } catch (Exception e) {
            // 表可能不存在
            fileCount = 0;
        }
        stats.put("fileCount", fileCount != null ? fileCount : 0);
        
        // 在线用户数（从Redis或Session获取，这里简化为查询今日登录用户数）
        Integer onlineCount = 0;
        try {
            onlineCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(DISTINCT user_name) FROM sys_logininfor WHERE DATE(login_time) = CURDATE() AND status = '0'", 
                Integer.class);
        } catch (Exception e) {
            onlineCount = 0;
        }
        stats.put("onlineCount", onlineCount != null ? onlineCount : 0);
        
        // 今日访问量
        Integer todayVisits = 0;
        try {
            todayVisits = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_logininfor WHERE DATE(login_time) = CURDATE()", Integer.class);
        } catch (Exception e) {
            todayVisits = 0;
        }
        stats.put("todayVisits", todayVisits != null ? todayVisits : 0);
        
        // 计算增长趋势（与昨日对比）
        Map<String, Double> trends = calculateTrends();
        stats.put("trends", trends);
        
        return success(stats);
    }
    
    /**
     * 计算增长趋势
     */
    private Map<String, Double> calculateTrends()
    {
        Map<String, Double> trends = new HashMap<>();
        
        // 用户增长趋势
        try {
            Integer todayUsers = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_user WHERE del_flag = '0' AND DATE(create_time) = CURDATE()", Integer.class);
            Integer yesterdayUsers = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_user WHERE del_flag = '0' AND DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)", Integer.class);
            trends.put("userTrend", calculatePercentage(todayUsers, yesterdayUsers));
        } catch (Exception e) {
            trends.put("userTrend", 0.0);
        }
        
        // 消息增长趋势
        try {
            Integer todayMessages = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_chat_message WHERE DATE(create_time) = CURDATE()", Integer.class);
            Integer yesterdayMessages = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_chat_message WHERE DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)", Integer.class);
            trends.put("messageTrend", calculatePercentage(todayMessages, yesterdayMessages));
        } catch (Exception e) {
            trends.put("messageTrend", 0.0);
        }
        
        // 文件增长趋势
        try {
            Integer todayFiles = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_file WHERE del_flag = '0' AND DATE(create_time) = CURDATE()", Integer.class);
            Integer yesterdayFiles = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_file WHERE del_flag = '0' AND DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)", Integer.class);
            trends.put("fileTrend", calculatePercentage(todayFiles, yesterdayFiles));
        } catch (Exception e) {
            trends.put("fileTrend", 0.0);
        }
        
        // 访问量增长趋势
        try {
            Integer todayVisits = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_logininfor WHERE DATE(login_time) = CURDATE()", Integer.class);
            Integer yesterdayVisits = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_logininfor WHERE DATE(login_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)", Integer.class);
            trends.put("visitTrend", calculatePercentage(todayVisits, yesterdayVisits));
        } catch (Exception e) {
            trends.put("visitTrend", 0.0);
        }
        
        return trends;
    }
    
    /**
     * 计算增长百分比
     */
    private Double calculatePercentage(Integer today, Integer yesterday)
    {
        if (today == null) today = 0;
        if (yesterday == null || yesterday == 0) {
            return today > 0 ? 100.0 : 0.0;
        }
        return Math.round((today - yesterday) * 1000.0 / yesterday) / 10.0;
    }
    
    /**
     * 获取访问趋势数据（最近7天）
     */
    @GetMapping("/visits/trend")
    public AjaxResult getVisitsTrend()
    {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取最近7天的日期和访问量
            var list = jdbcTemplate.queryForList(
                "SELECT DATE(login_time) as date, COUNT(*) as count " +
                "FROM sys_logininfor " +
                "WHERE login_time >= DATE_SUB(CURDATE(), INTERVAL 6 DAY) " +
                "GROUP BY DATE(login_time) " +
                "ORDER BY date"
            );
            result.put("data", list);
        } catch (Exception e) {
            result.put("data", new java.util.ArrayList<>());
        }
        
        return success(result);
    }
}
