<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use DispatchesJobs, ValidatesRequests;
    
    protected function jsonReturn($error, $msg, $data=NULL)
    {
        $result['error'] = $error;
        $result['message'] = $msg;
        $result['data'] = $data;
        return response()->json($result);
    }
    
    protected function errorAbort($errorCode, $errorMessage)
    {
        $viewData = [
            "error_code" => $errorCode,
            "error_message" => $errorMessage,
        ];
        return view("error.general", $viewData);
    }
    
    public function getClientRealIP()
    {
        $address = '';
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }else {
            $address = $_SERVER['REMOTE_ADDR'];
        }
        if ($address === "") {
            $address = '0.0.0.0';
            return $address;
        }
        
        if (strpos($address, ',') !== FALSE) {
            $x = explode(',', $address);
            $address = trim(current($x));
        }
        
        return $address;
    }

    protected function getSuccessMsg($data = array(), $msg = '操作成功', $needObject = true, $code = '200')
    {
        return response()->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data ? $data : ($needObject ? (object)array() : []),
        ]);
    }

    protected function getErrorMsg($code = '', $msg = '')
    {
        return response()->json([
            'code' => $code,
            'msg' => $msg,
        ]);
    }

    protected function view( $name, $data = array() )
    {
        return view($name, $data);
    }
}
