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

use plugin\saiadmin\app\cache\UserInfoCache;
use plugin\saiadmin\exception\ApiException;

/**
 * 基类 控制器继承此类
 */
class BaseController extends OpenController
{

    /**
     * 当前登陆管理员信息
     */
    protected $adminInfo;

    /**
     * 当前登陆管理员ID（未登录时为 null）
     */
    protected ?int $adminId = null;

    /**
     * 当前登陆管理员账号（未登录时为空字符串）
     */
    protected string $adminName = '';

    /**
     * 逻辑层注入
     */
    protected $logic;

    /**
     * 验证器注入
     */
    protected $validate;

    /**
     * 初始化
     */
    protected function init(): void
    {
        // 登录模式赋值：优先从中间件注入的 header 取，否则从 JWT 当前用户取
        $result = request()->header('check_admin');
        if (!is_array($result) || empty($result['id'])) {
            $result = getCurrentInfo();
        }
        if (is_array($result) && !empty($result['id'])) {
            $this->adminId = $result['id'];
            $this->adminName = $result['username'] ?? '';
            $this->adminInfo = UserInfoCache::getUserInfo($result['id']);
            if (empty($this->adminInfo) || !isset($this->adminInfo['id'])) {
                $this->adminInfo = UserInfoCache::setUserInfo($result['id']);
            }

            // 用户数据传递给逻辑层
            if ($this->logic && !empty($this->adminInfo)) {
                $this->logic->init($this->adminInfo);
            }
        }
    }

    /**
     * 确保当前请求已加载管理员信息（用于 init 未正确注入时的回退）
     * @return bool 是否已有有效的 adminInfo
     */
    protected function ensureAdminInfo(): bool
    {
        if ($this->adminInfo !== null && is_array($this->adminInfo) && isset($this->adminInfo['id'])) {
            return true;
        }
        $token = getCurrentInfo();
        if (!is_array($token) || empty($token['id'])) {
            return false;
        }
        $this->adminId = $token['id'];
        $this->adminName = $token['username'] ?? '';
        $this->adminInfo = UserInfoCache::getUserInfo($token['id']);
        if (empty($this->adminInfo) || !isset($this->adminInfo['id'])) {
            $this->adminInfo = UserInfoCache::setUserInfo($token['id']);
        }
        return is_array($this->adminInfo) && isset($this->adminInfo['id']);
    }

    /**
     * 验证器调用
     */
    protected function validate(string $scene, $data): bool
    {
        if ($this->validate) {
            if (!$this->validate->scene($scene)->check($data)) {
                throw new ApiException($this->validate->getError());
            }
        }
        return true;
    }

}
