<?php

namespace Modules\SystemUser\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User;
use Illuminate\Notifications\Notifiable;
use Laravel\Ai\Concerns\HasConversations;
use Laravel\Sanctum\HasApiTokens;
use Modules\SystemTool\Models\SysFileModel;

/**
 * 系统用户模型
 */
class SysUserModel extends User
{
    use SoftDeletes, HasConversations, HasApiTokens, HasFactory, Notifiable;

    protected $table = 'sys_user';
    protected $primaryKey = 'id';
    protected $fillable = [
        'username',
        'password',
        'nickname',
        'avatar_id',
        'bio',
        'sex',
        'mobile',
        'email',
        'email_verified_at',
        'dept_id',
        'login_ip',
        'login_time',
        'status'
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'login_time' => 'datetime',
        'status' => 'integer',
        'sex' => 'integer',
        'avatar_id' => 'integer',
        'dept_id' => 'integer'
    ];

    protected $appends = ['role_id', 'dept_name', 'avatar_url'];

    protected $with = ['dept', 'avatar'];

    protected $hidden = [
        'dept',
        'avatar',
        'password',
        'remember_token',
        'deleted_at',
    ];

    /**
     * 定义与部门的归属关系
     */
    public function dept(): BelongsTo
    {
        return $this->belongsTo(SysDeptModel::class, 'dept_id', 'id');
    }

    /** 部门名称 */
    public function getDeptNameAttribute(): string
    {
        return $this->dept->name ?? '';
    }

    /**
     * 定义与角色的关联
     */
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(SysRoleModel::class, 'sys_user_role', 'user_id', 'role_id');
    }

    /**
     * 获取用户角色列表
     */
    public function getRoleIdAttribute()
    {
        return $this->roles()
            ->pluck('id')->toArray();
    }

    /**
     * 定义与登录日志的关联
     */
    public function loginRecords(): HasMany
    {
        return $this->hasMany(SysLoginRecordModel::class, 'user_id', 'id');
    }

    /**
     * 关联用户头像
     * @return HasOne
     */
    public function avatar(): HasOne
    {
        return $this->hasOne(SysFileModel::class, 'id', 'avatar_id');
    }

    /**
     * 获取用户角色列表
     */
    public function getAvatarUrlAttribute()
    {
        if($this->avatar) {
            return $this->avatar->preview_url;
        }
        return null;
    }

    /**
     * 获取用户所有权限
     * @return array
     */
    public function access(): array
    {
        if($this->id == 1) {
            return SysRuleModel::query()
                ->where('status', 1)
                ->pluck('key')
                ->toArray();
        }
        $roles = SysUserModel::with(['roles.rules' => function ($query) {
            $query->where('status', 1);
        }])->find($this->id)->roles->toArray();

        return collect($roles)
            ->map(fn ($item) => $item['rules'] )
            ->collapse()
            ->map(fn ($item) => $item['key'] )
            ->unique()
            ->toArray();
    }
}
