<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2019/12/5
 * Time: 17:44
 */

namespace app\api\controller\base;

use app\common\service\WebService;
use think\Controller;
use think\exception\HttpResponseException;
use think\Request;

/**
 * 接口父类
 * Class
 * @package app\api\controller\base
 */
class Base extends Controller
{
    const ERR_CODE_LOGIN = 1;

    protected function _initialize()
    {
        (new WebService())->checkInstalled();
        header('Access-Control-Allow-Origin: *');//允许跨域,*星号表示所有的域都可以接受
        header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, x-token');//允许访问的header
    }

    /**
     * api成功的响应
     * @param $msg string 成功消息
     * @param $data null 响应数据
     * @param $err_code int 消息码
     */
    protected function json_success($msg = "success", $data = null, $err_code = 0)
    {
        //和success方法相比,没有显示跳转页面,直接响应了json
        //和success方法返回的code要一致,这样前端ajax不用修改就能兼容
        $result = [
            'code' => 1,
            'err_code' => $err_code,
            'msg' => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];
        throw new HttpResponseException(json($result));
    }

    /**
     * api失败的响应
     * @param $msg string 错误消息
     * @param null $data 响应数据
     * @param $err_code int 消息码
     */
    protected function json_error($msg = "error", $data = null, $err_code = 0)
    {
        $result = [
            'code' => 0,
            'err_code' => $err_code,
            'msg' => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];
        throw new HttpResponseException(json($result));
    }

}