<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: sai <1430792918@qq.com>
// +----------------------------------------------------------------------
namespace plugin\saiadmin\app\logic\system;

use plugin\saiadmin\app\model\system\SystemLoginLog;
use plugin\saiadmin\basic\think\BaseLogic;
use plugin\saiadmin\utils\Helper;
use support\think\Db;

/**
 * 登录日志逻辑层
 */
class SystemLoginLogLogic extends BaseLogic
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new SystemLoginLog();
    }

    /**
     * 登录统计图表
     * @return array
     */
    public function loginChart(): array
    {
        $sql = "
            SELECT
                d.date AS login_date,
                COUNT(l.login_time) AS login_count
            FROM
                (SELECT CURDATE() - INTERVAL (a.N) DAY AS date
                 FROM (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3
                       UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6
                       UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
                 ) d
            LEFT JOIN sa_system_login_log l
                ON DATE(l.login_time) = d.date
            GROUP BY d.date
            ORDER BY d.date ASC;
        ";
        $data = Db::query($sql);
        return [
            'login_count' => array_column($data, 'login_count'),
            'login_date' => array_column($data, 'login_date'),
        ];
    }

    /**
     * 登录统计图表
     * @return array
     */
    public function loginBarChart(): array
    {
        $sql = "
            SELECT
                -- 拼接成 YYYY-MM 格式，例如 2023-01
                CONCAT(LPAD(m.month_num, 2, '0'), '月') AS login_month,
                COUNT(l.login_time) AS login_count
            FROM
                -- 生成 1 到 12 的月份数字
                (SELECT 1 AS month_num UNION ALL SELECT 2 UNION ALL SELECT 3
                 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6
                 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
                 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12) m
            LEFT JOIN sa_system_login_log l
                -- 关联条件：年份等于今年 且 月份等于生成的数字
                ON YEAR(l.login_time) = YEAR(CURDATE())
                AND MONTH(l.login_time) = m.month_num
            GROUP BY
                m.month_num
            ORDER BY
                m.month_num ASC;
        ";
        $data = Db::query($sql);
        return [
            'login_count' => array_column($data, 'login_count'),
            'login_month' => array_column($data, 'login_month'),
        ];
    }

}
