<?php

namespace App\Models;

use App\Enums\UserStatus;
use App\Traits\BelongsToStore;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, SoftDeletes, BelongsToStore;

    protected $fillable = [
        'store_id', 'department_id', 'position_id',
        'username', 'password', 'name', 'phone', 'email',
        'avatar', 'status', 'is_super', 'last_login_at',
    ];

    protected $hidden = ['password'];

    protected function casts(): array
    {
        return [
            'status' => UserStatus::class,
            'is_super' => 'boolean',
            'last_login_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    public function department(): BelongsTo
    {
        return $this->belongsTo(Department::class);
    }

    public function position(): BelongsTo
    {
        return $this->belongsTo(Position::class);
    }

    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class, 'role_user');
    }

    /**
     * 获取用户所有权限标识
     */
    public function getAllPermissionCodes(): array
    {
        if ($this->is_super) {
            return ['*'];
        }

        return $this->roles()
            ->with('permissions')
            ->get()
            ->pluck('permissions')
            ->flatten()
            ->pluck('code')
            ->unique()
            ->values()
            ->toArray();
    }

    /**
     * 检查是否有指定权限
     */
    public function hasPermission(string $code): bool
    {
        if ($this->is_super) {
            return true;
        }

        return in_array($code, $this->getAllPermissionCodes());
    }

    /**
     * 获取用户菜单树
     */
    public function getMenuTree(): array
    {
        if ($this->is_super) {
            $menus = Menu::where('status', 1)->orderBy('sort')->get();
        } else {
            $permissionCodes = $this->getAllPermissionCodes();
            $menus = Menu::where('status', 1)
                ->where(function ($q) use ($permissionCodes) {
                    $q->whereIn('permission_code', $permissionCodes)
                      ->orWhereNull('permission_code');
                })
                ->orderBy('sort')
                ->get();
        }

        return self::buildTree($menus->toArray());
    }

    private static function buildTree(array $items, int $parentId = 0): array
    {
        $tree = [];
        foreach ($items as $item) {
            if ($item['parent_id'] == $parentId) {
                $children = self::buildTree($items, $item['id']);
                if ($children) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }
}
