<?php

namespace App\Http\Controllers\api;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Lang;

class BaseController extends Controller
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    protected $lang = 'zh';

    public function __construct()
    {
        $lang = request()->input('lang');
        if (!$lang) {
            $lang = request()->header('Lang', 'zh');
        }
        App::setLocale($lang);
        $this->lang = $lang;
    }

    protected function success($data = [], $msg = 'messages.ok')
    {
        return response()->json([
            'code' => 0,
            'timestamp' => time(),
            'msg' => Lang::get($msg),
            'data' => $data
        ]);
    }

    protected function error(string $msg = "请求错误", $data = [], int $code = -1)
    {
        $code = intval($code);
        if ($code === 0) $code = -1;
        $a = Lang::get("messages.{$msg}", $data);
        if ($a == "messages." . $msg) {
            $a = $msg;
        }

        return response()->json([
            'code' => $code,
            'timestamp' => time(),
            'msg' => $a,
            'data' => $data
        ]);
    }


}