<?php

namespace App\Http\Controllers;

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

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    //成功返回
    public function success($data,$msg="ok")
    {
        $this->parseNull($data);
        $result = [
            "code"=>200,
            "msg"=>$msg,
            "data"=>$data,
        ];
        return response()->json($result,200);
    }
    //成功返回带数量
    public function success_list($data,$msg="ok",$total=0){
        $data=!is_array($data)?collect($data)->toArray():$data;
        $this->parseNull($data);
        $result = [
            "code"=>200,
            "msg"=>$msg,
            "data"=>[
                'total'=>$total,
                'list'=>$data
            ],
        ];
        return response()->json($result,200);
    }

    //失败返回
    public function error($code="422",$msg="fail",$data=""){
        $result = [
            "code"=>$code,
            "msg"=>$msg,
            "data"=>$data
        ];
        return response()->json($result,200);
    }

    //如果返回的数据中有 null 则那其值修改为空 （安卓和IOS 对null型的数据不友好，会报错）
    private function parseNull(&$data){
        if(is_array($data)){
            foreach($data as &$v){
                $this->parseNull($v);
            }
        }else{
            if(is_null($data)){
                $data = "";
            }
        }
    }




}
