<?php

namespace App\Http\Controllers\V1;

use Dingo\Api\Routing\Helpers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Client\Response;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Services\Base\ErrorCode;
use Request, Auth,Log;

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

    protected $_user = null;

    public function __construct()
    {
        //将用户选择的语言存进用户表
        $user = auth('api')->user();
        if($user){
            $lang = request()->header('lang','en');
            $user->lang = $lang;
            $user->save();
        }
    }



    private function genApiData($data, $code = 0, $msg = '') {
        if ($code !== 0 && ErrorCode::CLIENT_WRONG_PARAMS && empty($msg)) {
            $msg = ErrorCode::message($code);
        }
        $ret = [
            'code'   => $code,
            'msg'    => $msg,
            'data'   => $data
        ];
        return $ret;
    }

    public function success($data=null,$code=0,$msg = null)
    {
        if(!$msg) $msg = trans('api.SUCCESS');
        return $this->api($data, $code, $msg);
    }

    public function error($msg = null,$code=1, $data = null) {
        return $this->api($data, $code, $msg);
    }

    public function api($data, $code = 0, $message = '') {
        //$ret = $this->genApiData($data, $code, $message);
        $ret = [
            'code'   => $code,
            'msg'    => $message,
            'data'   => $data
        ];
        return response()->json($ret);
    }

    public function validatorError($arr, $code = 1, $message = '')
    {
        foreach ($arr as $val){
            if($val&&$message==''){
                $message = $val;
            }
        }
        $ret = $this->genApiData(null, $code, $message);
        return response()->json($ret);
    }





}
