<?php

declare (strict_types=1);

namespace library\utils;

use library\services\JsonNull;
use think\facade\Config;
use think\facade\Lang;
use think\Response;

/**
 * Json输出类
 * Class Json
 * @package crmeb\utils
 */
class Json
{
    private $code = 200;

    public function code(int $code): self
    {
        $this->code = $code;
        return $this;
    }

    public function make(int $code, string $msg, ?array $data = null): Response
    {
        $request = app()->request;
        $res     = compact('code', 'msg');

        if (!is_null($data))
            $res['data'] = $data;
        else
            $res['data'] = new JsonNull;

        if ($res['msg'] && !is_numeric($res['msg'])) {
            if (!$range = $request->get('lang')) {
                $range = $request->cookie(Config::get('lang.cookie_var'));
            }
            $res['msg'] = Lang::get($res['msg'], [], $range !== 'deleted' && $range ? $range : 'zh-cn');
        }
        //Null处理
        $res = $this->JsonNull($res);
        return Response::create($res, 'json', $this->code)->header(["Content-type" => "text/html;charset=utf-8;"]);
    }

    public function success($msg = 'ok', ?array $data = null): Response
    {
        if (is_array($msg)) {
            $data = $msg;
            $msg  = 'ok';
        }

        return $this->make(200, $msg, $data);
    }

    public function successful(...$args): Response
    {
        return $this->success(...$args);
    }

    public function fail($msg = 'fail', ?array $data = null): Response
    {
        if (is_array($msg)) {
            $data = $msg;
            $msg  = 'ok';
        }

        return $this->make(-1, $msg, $data);
    }

    public function status($status, $msg, $result = [])
    {
        $status = strtoupper($status);
        if (is_array($msg)) {
            $result = $msg;
            $msg    = 'ok';
        }
        return $this->success($msg, compact('status', 'result'));
    }

    /**
     * 处理Json Null Bug字符串
     * @param array|null $data
     * @return array
     */
    public function JsonNull(?array $data): array
    {
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                $v = $this->JsonNull($v);
            } else {
                if ($v instanceof JsonNull) {
                    $v = null;
                } else if (is_null($v)) {
                    $v = '';
                }
            }
            $data[$k] = $v;
        }
        return $data;
    }


}