<?php

namespace App\Http\Controllers\V1;

use Dingo\Api\Routing\Helpers;
use Illuminate\Foundation\Bus\DispatchesJobs;
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;

    //验证器错误信息返回
    public function validatorError($arr, $code = 0, $msg = '')
    {
        //写入日志
        Log::info($arr);
        //获取返回信息
        foreach ($arr as $val){
            if($val&&$msg==''){
                $msg = $val;
            }
        }
        //组装状态码和返回信息
        $res = [
            'code' => $code,
            'msg'  => $msg ?? '',
            'data' => null
        ];
        //json返回数据和状态码
        return response()->json($res);
    }

    //通用输出方法
    public function output($data=[], $code = 0, $msg = '')
    {
        $ret = $this->makeApiData($data, $code, $msg);
        return response()->json($ret);
    }

    //正确返回
    public function success($data=[], $code = 0, $msg = '')
    {
        //是否有成功时返回的信息
        if (!$msg) $msg = trans('api.SUCCESS');
        //组装状态码返回信息等数据
        $ret = $this->makeApiData($data, $code, $msg);
        //返回json数据
        return response()->json($ret);
    }

    //错误返回
    public function error($msg = '', $code = 1,  $data = null)
    {
        $ret = $this->makeApiData($data, $code, $msg);
        return response()->json($ret);
    }

    //生成返回数据
    private function makeApiData($data, $code = 0, $message = '')
    {
        //判断状态码是否正常和返回信息是否为空
        if ($code !== 0 && empty($message)) {
            //输出错误码对应的错误信息
            $message = ErrorCode::message($code);
        } else if ($code == 0 && empty($message)) {
            //输出成功信息
            $message = 'success';
        }
        //组装数据
        $ret = [
            'code' => $code,
            'msg'  => $message,
            'data' => $data
        ];
        //返回数据
        return $ret;
    }

    // 分页
    public function page($list){
        return [
            'items' =>$list->items(),
            'total'=>$list->total(),   // 总数
            'pageSize'=>$list->perPage(), // 每页数据
            'totalPage'=>$list->lastPage(),// 总页数
            'page'=>$list->currentPage(),//当前页
        ];
    }
}
