<?php

namespace App\Exception;

use Helpers\ApiResponse;
use Yaf\Registry;

/**
 * Class BaseException
 * 自定义异常类的基类
 */
class BaseException extends \Exception
{
    use ApiResponse;

    public $msg;
    public $code;

    /**
     * 构造函数，接收一个关联数组
     * @param array $params 关联数组只应包含code、msg和errorCode，且不应该是空值
     */
    public function __construct($params = [])
    {
        if (empty($params)) {
            return;
        }
        if (!is_array($params)) {
            return $this->setCusMsg($params);
        }

        $this->code = $params['code'] ?? Registry::get('config')->exception->user->code;
        $this->msg = $params['msg'] ?? Registry::get('config')->exception->user->msg;

        if (isset($params['cus']) && $this->cus && isset($this->cus[intval($params['cus'])]) && $this->base_code) {
            return $this->setCusMsg($params['cus'],$params['data']??'');
        }
    }

    public function setCusMsg($cus,$data = '')
    {
        //每个服务都有自己的codePrefix
        $appid = \Yaf\Application::app()->getConfig()->get("appid");
        $codePrefix = \Yaconf::get('bizcode.prefix.' . $appid);
        $codePrefix = intval($codePrefix);

        $cus_code = intval($cus);
        $base_code = intval($this->base_code);

        $this->code = $codePrefix + $base_code + $cus_code;
        $this->msg = !empty($data) ? vsprintf($this->cus[$cus_code],$data) : $this->cus[$cus_code];
    }

    public function __get($name): bool
    {
        return false;
    }
}
