<?php
!defined('EMLOG_ROOT') && exit('Hacker!');

class DYBOYBlogDashboard
{
  private static $_instance;
  private $db;

  // 构造函数初始化 DB
  public function __construct()
  {
    $this->db = Database::getInstance();
  }

  public static function getInstance()
  {
    if (!(self::$_instance instanceof self)) {
      self::$_instance = new self();
    }
    return self::$_instance;
  }

  private function get_base_data()
  {
    $CACHE = Cache::getInstance();
    $data = $CACHE->readCache('sta');
    if (!$data) {
      return [];
    }
    // 输出详细的信息到页面上
    echo '<pre>';
    print_r($data);
    echo '</pre>';
    return $data;
  }

  private function get_post_count_by_day()
  {
    // 获得 15 天前的时间戳
    $start_time = time() - 15 * 24 * 60 * 60;
    $sql = "SELECT 
              DATE(FROM_UNIXTIME(date)) AS date,
              COUNT(*) AS post_count,
              SUM(views) AS total_views,
              SUM(comnum) AS total_comments,
              SUM(like_count) AS total_likes
            FROM " . DB_PREFIX . "blog 
            WHERE hide='n' AND date > $start_time
            GROUP BY DATE(FROM_UNIXTIME(date)) 
            ORDER BY DATE(FROM_UNIXTIME(date)) DESC";
    $result = $this->db->query($sql);
    $data = [];
    while ($row = $this->db->fetch_array($result)) {
      $data[] = $row;
    }
    // 填充缺失日期的数据
    $filled_data = [];
    $end_date = date('Y-m-d');
    $start_date = date('Y-m-d', time() - 14 * 24 * 60 * 60); // 15天前的日期

    // 将查询结果转换为以日期为键的数组
    $date_data = array();
    foreach ($data as $row) {
      $date_data[$row['date']] = $row;
    }

    // 遍历日期范围，填充缺失的数据
    $current_date = $start_date;
    while (strtotime($current_date) <= strtotime($end_date)) {
      if (isset($date_data[$current_date])) {
        $filled_data[] = $date_data[$current_date];
      } else {
        $filled_data[] = array(
          'date' => $current_date,
          'post_count' => '0',
          'total_views' => '0',
          'total_comments' => '0',
          'total_likes' => '0',
          'total_attachments' => '0'
        );
      }
      $current_date = date('Y-m-d', strtotime($current_date . ' +1 day'));
    }

    return $filled_data; // 保持降序排列
  }

  private function get_new_user_count_by_day()
  {
    $sql = "SELECT DATE(FROM_UNIXTIME(create_time)) AS date, COUNT(*) AS user_count FROM " . DB_PREFIX . "user GROUP BY DATE(FROM_UNIXTIME(create_time)) ORDER BY DATE(FROM_UNIXTIME(create_time)) DESC";
    $result = $this->db->query($sql);
    $data = [];
    while ($row = $this->db->fetch_array($result)) {
      $data[] = $row;
    }

    // 填充缺失日期的数据
    $filled_data = [];
    $end_date = date('Y-m-d');
    $start_date = date('Y-m-d', time() - 14 * 24 * 60 * 60); // 15天前的日期

    // 将查询结果转换为以日期为键的数组
    $date_data = array();
    foreach ($data as $row) {
      $date_data[$row['date']] = $row;
    }

    // 遍历日期范围，填充缺失的数据
    $current_date = $start_date;
    while (strtotime($current_date) <= strtotime($end_date)) {
      if (isset($date_data[$current_date])) {
        $filled_data[] = $date_data[$current_date];
      } else {
        $filled_data[] = array(
          'date' => $current_date,
          'user_count' => '0'
        );
      }
      $current_date = date('Y-m-d', strtotime($current_date . ' +1 day'));
    }

    return $filled_data; // 保持降序排列
  }

  public function dyboy_blog_dashboard_dashboard()
  {
    $data = $this->get_post_count_by_day();
    $new_user_data = $this->get_new_user_count_by_day();
    global $user_cache;
    $total_user_count = count($user_cache);
    echo '
    <script>script=document.createElement("script");script.src="https://unpkg.com/@visactor/vchart/build/index.min.js";script.onload=function(){render_posts_trend();render_new_users_trend()};document.head.appendChild(script);</script>';
    echo '<div class="col-lg-6 mb-3"><div class="card shadow mb-3"><h6 class="card-header">近 15 天文章数据趋势图</h6><div class="card-body"><div id="posts-trend-chart" style="width: 100%; height: 300px;"></div></div></div></div><div class="col-lg-6 mb-3"><div class="card shadow mb-3"><h6 class="card-header">近 15 天用户数据趋势图</h6><div class="card-body"><div id="new-users-trend-chart" style="width: 100%; height: 300px;"></div></div></div></div>';
    echo '<script>var commonLineChartConfig = {type: "line",xField: "date",yField: "value",seriesField: "type",label: {visible:true, formatMethod:(text)=>Number(text)?text:""},legends: [{visible:true}],line:{style:{curveType:"monotone"}},point:{visible:true,style:{size:0},state: {dimension_hover: {size: 10}}}};function render_posts_trend() {var parsedData = (' . json_encode($data) . '||[]).map(i => {return [{date: i.date, value: Number(i.post_count)||0, type: "发文数量"}, {date: i.date, value: Number(i.total_views)||0, type: "浏览量"}, {date: i.date, value: Number(i.total_comments)||0, type: "评论量"}, {date: i.date, value: Number(i.total_likes)||0, type: "点赞量"}]});parsedData = parsedData.flat();var posts_data = Object.assign({},commonLineChartConfig,{data: [{values: parsedData}]});var chart = new VChart.default(posts_data, {dom: "posts-trend-chart"});chart.renderSync();};function render_new_users_trend() {var total_user_count = '. $total_user_count .';var originData = '. json_encode($new_user_data) .'||[];var dates = originData.map(i => i.date);let newUserCount = 0;var totalAddCount = 0;var addUsersCount = dates.map((_,idx)=> {totalAddCount+=Number(originData[idx].user_count)||0;return Number(originData[idx].user_count)||0;});var initUserCount = total_user_count - totalAddCount;var totalUserCountData = dates.map((i,idx) => {return {date: i, value: initUserCount+=addUsersCount[idx], type: "总用户数"}});var parsedData = originData.map(i => {return [{date: i.date, value: Number(i.user_count)||0, type: "新增用户"}]});parsedData = parsedData.flat();var new_users_data = Object.assign({},commonLineChartConfig,{data: [{values: parsedData.concat(totalUserCountData)}]});var chart = new VChart.default(new_users_data, {dom: "new-users-trend-chart"});chart.renderSync();};</script>';
  }
}