<?php
/**
 * Base.php UTF-8
 * 基础函数
 *
 * @date    : 2017/11/16 17:23
 *
 * @license 这不是一个自由软件,未经授权不许任何使用和传播。
 * @author  : wuyonghong <wyh@huosdk.com>
 * @version : HUOSDK 8.0
 */

namespace huo\controller\common;

use huolib\status\CommonStatus;
use think\Log;

class Base {
    protected $code = 200;
    protected $msg  = '';
    protected $data = [];

    /**
     * 实例化
     *
     * @return static
     */
    public static function ins() {
        return new static();
    }

    /**
     * log 记录所有错误信息
     *
     * @param mixed  $msg 输出的异常信息
     * @param string $level
     *
     */
    protected function errorLog($msg, $level = 'error') {
        Log::write($msg, $level);
    }

    /**
     * 返回码
     *
     * @access public
     * @return int
     */
    public function getCode() {
        return $this->code;
    }

    /**
     * @param int $code
     */
    public function setCode($code) {
        $this->code = $code;
    }

    /**
     * @return string
     */
    public function getMessage() {
        return $this->msg;
    }

    /**
     * @param string $msg
     */
    public function setMsg($msg) {
        $this->msg = $msg;
    }

    /**
     * @return array
     */
    public function getData() {
        return $this->data;
    }

    /**
     * @param mixed $data
     */
    public function setData($data) {
        $this->data = $data;
    }

    /**
     * 返回错误信息
     *
     * @param int    $code
     * @param string $msg
     * @param array  $data
     *
     * @return array
     */
    public function huoError($code = 400, $msg = '', $data = []) {
        return $this->huoSuccess($code, $msg, $data);
    }

    /**
     * 逻辑处理返回信息
     *
     * @param int    $code
     * @param string $msg
     * @param array  $data
     *
     * @return array
     */
    public function huoSuccess($code = 200, $msg = '', $data = []) {
        $_rdata['code'] = $code;
        $_rdata['msg'] = $msg;
        $_rdata['data'] = $data;

        return $_rdata;
    }

    /**
     * @param mixed $_data
     */
    public function huoReturn($_data) {
        return $this->huoSuccess($_data['code'], $_data['msg'], $_data['data']);
    }

    /**
     * @param array      $data
     * @param string|int $key
     * @param string     $default
     *
     * @return string
     */
    protected function getVal($data, $key, $default = '') {
        if (empty($key) || empty($data) || !isset($data[$key])) {
            return $default;
        }

        return $data[$key];
    }

    /**
     * @param int   $code
     * @param array $data
     *
     * @return array
     */
    protected function retSucMsg($code, $data = []) {
        $_msg = CommonStatus::getMsg($code);

        return $this->huoSuccess($code, $_msg, $data);
    }

    /**
     * @param $code
     *
     * @return mixed
     */
    protected function retErrMsg($code) {
        $_err_msg = CommonStatus::getMsg($code);

        return $this->huoError($code, $_err_msg);
    }
}