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

use app\api\util\ApiLang;
use support\Request;
use support\Response;

/**
 * 基类 控制器继承此类
 */
class OpenController
{
    /**
     * 构造方法
     * @access public
     */
    public function __construct()
    {
        // 控制器初始化
        $this->init();
    }

    /**
     * 成功返回json内容
     * @param array|string $data
     * @param string $msg
     * @param int $option
     * @return Response
     */
    public function success(array | string $data = [], string $msg = 'success', int $option = JSON_UNESCAPED_UNICODE): Response
    {
        if (is_string($data)) {
            $msg = $data;
        }
        $msg = ApiLang::translate($msg, request());
        return json(['code' => 200, 'message' => $msg, 'data' => $data], $option);
    }

    /**
     * 失败返回json内容
     * @param string $msg
     * @param int $code 201=请携带token 202=缺少参数 203=token过期，默认400
     * @return Response
     */
    public function fail(string $msg = 'fail', int $code = 400): Response
    {
        $msg = ApiLang::translate($msg, request());
        return json(['code' => $code, 'message' => $msg]);
    }

    /**
     * 初始化
     */
    protected function init(): void
    {
        // TODO
    }

}