<?php

namespace App\Models;

use Carbon\Carbon;

/**
 * 用户登录日志（只读侧：bot-28 后台查询）
 *
 * 写入在 melbet_sport-api 完成。
 * - user_id：仅真实用户 ID，失败且无用户时为空字符串
 * - login_account：尝试登录账号
 * - online_duration：仅登出后落库；未登出时接口通过 online_duration_live 估算
 */
class UserLogin extends BaseModel
{
    protected $table = 'user_login';

    protected $fillable = [
        'user_id',
        'login_account',
        'login_ip',
        'login_domain',
        'country',
        'browser',
        'os',
        'platform',
        'status',
        'logout_time',
        'online_duration',
        'user_agent',
    ];

    // 登录日志需要展示登录时间
    protected $hidden = [];

    protected $appends = ['status_text', 'is_online', 'online_duration_live'];

    public const STATUS_FAIL = 0;
    public const STATUS_SUCCESS = 1;

    public function getStatusTextAttribute(): string
    {
        return (int)($this->attributes['status'] ?? self::STATUS_FAIL) === self::STATUS_SUCCESS
            ? '登录成功'
            : '登录失败';
    }

    public function getIsOnlineAttribute(): bool
    {
        if ((int)($this->attributes['status'] ?? self::STATUS_FAIL) !== self::STATUS_SUCCESS) {
            return false;
        }
        $logout = $this->attributes['logout_time'] ?? null;
        return empty($logout) || $logout === '0000-00-00 00:00:00';
    }

    /**
     * 展示用在线时长（分钟）：
     * - 已登出：库内 online_duration
     * - 仍在线：按登录时间估算（不写库）
     * - 失败：null
     */
    public function getOnlineDurationLiveAttribute(): ?int
    {
        if ((int)($this->attributes['status'] ?? self::STATUS_FAIL) !== self::STATUS_SUCCESS) {
            return null;
        }

        $stored = $this->attributes['online_duration'] ?? null;
        if ($stored !== null && $stored !== '') {
            return (int)$stored;
        }

        if (!$this->is_online) {
            return null;
        }

        $rawCreated = $this->attributes['created_at'] ?? null;
        if (empty($rawCreated)) {
            return null;
        }

        $loginTs = strtotime((string)$rawCreated);
        if (!$loginTs) {
            return null;
        }

        return (int)ceil(max(0, time() - $loginTs) / 60);
    }

    public function getLogoutTimeAttribute($value): ?string
    {
        if (empty($value) || $value === '0000-00-00 00:00:00') {
            return null;
        }
        return Carbon::parse($value)->setTimezone('Asia/Shanghai')->format('Y-m-d H:i:s');
    }

    // 获取用户未登录天数(最后第二次登录间隔天数)
    public static function getNotLoginDays($memberId)
    {
        $list = self::where('user_id', $memberId)
            ->where('status', self::STATUS_SUCCESS)
            ->orderByDesc('id')
            ->limit(2)
            ->get()
            ->toArray();
        if (count($list) < 2) {
            return 0;
        }
        if (date('Y-m-d', strtotime($list[0]['created_at'])) != date('Y-m-d')) {
            return 0;
        }
        $diff = strtotime($list[0]['created_at']) - strtotime($list[1]['created_at']);
        $days = ceil($diff / 86400);
        return abs($days);
    }
}
