<?php
// +----------------------------------------------------------------------
// | HkCms API总控制器
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2021 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace app\api\controller;

use app\admin\model\routine\Config;
use think\App;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use think\Validate;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [
        'api_login',
        'api_auth'
    ];

    /**
     * 配置
     * @var \think\Config
     */
    protected $config;

    /**
     * 缓存
     * @var \think\Cache
     */
    protected $cache;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app = $app;
        $this->request = $this->app->request;
        $this->config = $this->app->config;
        $this->cache = $this->app->cache;

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {
        // 初始化站点配置
        $site = Config::initConfig();

        $site = array_merge([
            'root_domain' => $this->request->baseFile(true), // 域名地址
            'root_file' => trim($this->request->baseFile(), '/'), // 入口文件
        ], $site);

        // 多语言内容配置
        $lang = $site['content_lang_on']==1?$this->app->lang->getLangset():'';
        $this->config->set($site, 'api'.$lang.'_site');

        // 加载当前控制器语言包
        loadlang($this->request->controller());

        hook('configInit', $site);
        // 定位模板位置
        $this->app->view->config(['view_path'=>root_path().'app'.DIRECTORY_SEPARATOR.'api'.DIRECTORY_SEPARATOR.'view'.DIRECTORY_SEPARATOR]);
        $this->app->view->assign('site', site());
    }

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

    /**
     * 返回（json/xml/jsonp）给到客户端
     * @param $msg string 提示信息
     * @param array $data 返回的数据
     * @param int $code 错误码
     * @param string $type 类型，json/xml/jsonp
     * @param array $header header信息
     */
    protected function result($msg, $data = [], $code = 0, $type = 'json', array $header=[])
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];

        $response = Response::create($result, $type)->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 操作失败的提示
     * @param string $msg
     * @param array $data
     * @param int $code
     * @param string $type
     * @param array $header
     */
    protected function error($msg, $data = [], $code = -1000, $type = 'json', array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 操作成功的提示
     * @param string $msg
     * @param array $data
     * @param int $code
     * @param string $type
     * @param array $header
     */
    protected function success($msg, $data = [], $code = 200, $type = 'json', array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }
}
