<?php
declare (strict_types = 1);

namespace app;

use think\App;
use think\exception\ValidateException;
use think\Validate;
use app\model\UserBehaviorLogModel;
use think\facade\Request;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    protected array $userInfo = [];
    protected int $userId = 0;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();      
    }

    // 初始化
    protected function initialize()
    {
        // 从中间件注入的用户信息
        if (isset($this->request->userInfo)) {
            $this->userInfo = $this->request->userInfo;
            $this->userId = $this->request->userId;
        }          
    }

    /**
     * 获取当前用户ID
     */
    protected function getUserId(): int
    {
        return $this->userId;
    }
    
    /**
     * 获取当前用户信息
     */
    protected function getUserInfo(): array
    {
        return $this->userInfo;
    }
    
    /**
     * 记录操作日志
     * @param int $status 操作状态
     * @param array $filterParams 需要过滤的参数键名（如密码等敏感信息）
     * @return bool
     */
    protected function recordBehavior(int $status = UserBehaviorLogModel::STATUS_SUCCESS, array $filterParams = ['password']): bool
    {
        try {
            // 获取用户信息
            $userInfo = $this->getUserInfo();
            if (empty($userInfo)) {
                return false;
            }
            
            // 获取控制器和方法名
            $controller = Request::controller();
            $action = Request::action();
            $behavior = $controller . '/' . $action;
            
            // 获取权限配置中的行为描述
            $permissions = config('permission.permissions');
            $behaviorText = '';
            if (isset($permissions[$controller]['actions'][$action])) {
                $behaviorText = $permissions[$controller]['module'] . '-' . $permissions[$controller]['actions'][$action];
            } else {
                $behaviorText = $behavior;
            }
            
            // 获取请求参数并过滤敏感信息
            $params = Request::param();
            foreach ($filterParams as $key) {
                if (isset($params[$key])) {
                    unset($params[$key]);
                }
            }
            
            // 构建日志数据
            $data = [
                'merchant_id' => $userInfo['merchant_id'] ?? 0,
                'user_id' => $userInfo['user_id'] ?? 0,
                'behavior' => $behaviorText,
                'behavior_desc' => json_encode($params, JSON_UNESCAPED_UNICODE),
                'behavior_ip' => getClientIp(),
                'behavior_url' => Request::url(true),
                'behavior_status' => $status
            ];
            
            // 记录日志
            return UserBehaviorLogModel::recordBehavior($data);
        } catch (\Exception $e) {
            // 记录日志失败不影响业务
            return false;
        }
    }

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, string|array $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

}
