<?php

namespace app\common\controller;

use app\common\library\Auth;
use think\Config;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Hook;
use think\Lang;
use think\Loader;
use think\Request;
use think\Response;
use think\Route;
use think\Validate;
use Redis;

/**
 * API控制器基类
 */
class Api
{

    /**
     * @var Request Request 实例
     */
    protected $request;

    /**
     * @var bool 验证失败是否抛出异常
     */
    protected $failException = false;

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

    /**
     * @var array 前置操作方法列表
     */
    protected $beforeActionList = [];

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 权限Auth
     * @var Auth
     */
    protected $auth = null;

    /**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';

    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        $this->request = is_null($request) ? Request::instance() : $request;

        if(config('site.apisite_switch') == 0){
            $notice = config('site.apisite_notice') ?: '全站维护中';
            $this->error($notice);
        }

        // 验签
        $this->apiverifysign();

        // 控制器初始化
        $this->_initialize();
        //日志
        $this->request_log();

        // 前置操作方法
        if ($this->beforeActionList) {
            foreach ($this->beforeActionList as $method => $options) {
                is_numeric($method) ?
                    $this->beforeAction($options) :
                    $this->beforeAction($method, $options);
            }
        }
    }


    //验签,2048位,265截取
    public function apiverifysign(){

        /*$ip = request()->ip();
        if($ip == '127.0.0.1'){
            return true;
        }*/
        //$modulename     = $this->request->module();
        //$controllername = $this->request->controller();
        $actionname     = $this->request->action();
        if (in_array($actionname,['upload','uploads','recognizingsounds','alipaynotify','trtc_callback','callback'])) {
            return true;
        }

        //解密签名开始
        $sign = $this->request->request('sign','','trim');
        if(empty($sign)){
            $this->error('缺少签名');
        }
        $sign = base64_decode($sign);

        $private_key_str = config('app_rsa.private_key');
        $private_key = "-----BEGIN RSA PRIVATE KEY-----" .PHP_EOL.
            wordwrap($private_key_str, 64, PHP_EOL, true) .
            PHP_EOL."-----END RSA PRIVATE KEY-----";

        $signgetdata = []; //被解密出来的数据
        $split_len = 256;
        $sign_split = str_split($sign, $split_len);
        foreach($sign_split as $key => $sign_val){
            $signgetdata_child = null;
            openssl_private_decrypt($sign_val, $signgetdata_child, $private_key); // 使用私钥解密数据
            $signgetdata[] = $signgetdata_child;
        }

        $signgetdata = implode('',$signgetdata);

        if (!$signgetdata) {
            $this->error('签名错误1');
        }
        //dump($signgetdata);
        //解密签名结束


        //接收到的参数,组成我自己的验签体string
        $request_all = $this->request->request();
        unset($request_all['s']);
        unset($request_all['sign']);
        ksort($request_all);

        $request_str = '';
        foreach($request_all as $key => $param){
            $request_str .= $key.'='.$param.'&';
        }
        $request_str .= 'signkey=F_dC923_35270PdsIIUIUTRERYTYYU';
        //dump($request_str);

        //作对比
        if($request_str != $signgetdata){
            $this->error('验签错误');
        }

        //echo '验签正确';
        return true;
    }



    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin');

        //跨域请求检测
//        check_cors_request();

        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');

        $this->auth = Auth::instance();

        $modulename = $this->request->module();
        $controllername = Loader::parseName($this->request->controller());
        $actionname = strtolower($this->request->action());

        // token
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));

        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        // 设置当前请求的URI
        $this->auth->setRequestUri($path);
        // 检测是否需要验证登录
        if (!$this->auth->match($this->noNeedLogin)) {
            //初始化
            $this->auth->init($token);
            //检测是否登录
            if (!$this->auth->isLogin()) {
                $this->error(__('Please login first'), null, 401);
            }
            // 判断是否需要验证权限
            /*if (!$this->auth->match($this->noNeedRight)) {
                // 判断控制器和方法判断是否有对应权限
                if (!$this->auth->check($path)) {
                    $this->error(__('You have no permission'), null, 403);
                }
            }*/
        } else {
            // 如果有传递token才验证是否登录状态
            if ($token) {
                $this->auth->init($token);
            }
        }

        $upload = \app\common\model\Config::upload();

        // 上传信息配置后
        Hook::listen("upload_config_init", $upload);

        Config::set('upload', array_merge(Config::get('upload'), $upload));

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

    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
        $name = Loader::parseName($name);
        Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
    }

    /**
     * 操作成功返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码,默认为1
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
    {
        if($msg == 1){
            $msg = 'success';
        }
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 操作失败返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码,默认为0
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码,默认为0
     * @param string $type   输出类型,支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];

        //日志
        $this->request_log_update($result);

        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 前置操作
     * @access protected
     * @param string $method  前置操作方法名
     * @param array  $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
     * @return void
     */
    protected function beforeAction($method, $options = [])
    {
        if (isset($options['only'])) {
            if (is_string($options['only'])) {
                $options['only'] = explode(',', $options['only']);
            }

            if (!in_array($this->request->action(), $options['only'])) {
                return;
            }
        } elseif (isset($options['except'])) {
            if (is_string($options['except'])) {
                $options['except'] = explode(',', $options['except']);
            }

            if (in_array($this->request->action(), $options['except'])) {
                return;
            }
        }

        call_user_func([$this, $method]);
    }

    /**
     * 设置验证失败后是否抛出异常
     * @access protected
     * @param bool $fail 是否抛出异常
     * @return $this
     */
    protected function validateFailException($fail = true)
    {
        $this->failException = $fail;

        return $this;
    }

    /**
     * 验证数据
     * @access protected
     * @param array        $data     数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array        $message  提示信息
     * @param bool         $batch    是否批量验证
     * @param mixed        $callback 回调方法(闭包)
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
    {
        if (is_array($validate)) {
            $v = Loader::validate();
            $v->rule($validate);
        } else {
            // 支持场景
            if (strpos($validate, '.')) {
                list($validate, $scene) = explode('.', $validate);
            }

            $v = Loader::validate($validate);

            !empty($scene) && $v->scene($scene);
        }

        // 批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }
        // 设置错误信息
        if (is_array($message)) {
            $v->message($message);
        }
        // 使用回调验证
        if ($callback && is_callable($callback)) {
            call_user_func_array($callback, [$v, &$data]);
        }

        if (!$v->check($data)) {
            if ($this->failException) {
                throw new ValidateException($v->getError());
            }

            return $v->getError();
        }

        return true;
    }

    /**
     * 刷新Token
     */
    protected function token()
    {
        $token = $this->request->param('__token__');

        //验证Token
        if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
            $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
        }

        //刷新Token
        $this->request->token();
    }

    /**
     * 判断当前url是否为全路径,并返回全路径
     */
    public function httpurl($path) {
        // 获取当前域名
        if(strpos($path,'http://') === false && strpos($path,'https://') === false) {
            $host = config("cos")['url'];
            $url = $host.$path;
        } else {
            $url = $path;
        }
        return $url;
    }

    /**
     * 判断当前url是否为全路径,并返回全路径
     */
    public function httpurlLocal($path) {
        // 获取当前域名
        if(strpos($path,'http://') === false && strpos($path,'https://') === false) {
            $host = $_SERVER["REQUEST_SCHEME"]."://".$_SERVER["HTTP_HOST"];
            $url = $host.$path;
        } else {
            $url = $path;
        }
        return $url;
    }

    /**
     * 接口请求限制
     * @param int $apiLimit
     * @param int $apiLimitTime
     * @param string $key
     * @return bool | true:通过 false:拒绝
     */
    public function apiLimit($apiLimit = 1, $apiLimitTime = 1000, $key = '')
    {
        $userId = $this->auth->id;
        $controller = request()->controller();
        $action = request()->action();

        if (!$key) {
            $key = strtolower($controller) . '_' . strtolower($action) . '_' . $userId;
        }

        $redis = new Redis();
        $redisconfig = config("redis");
        $redis->connect($redisconfig["host"], $redisconfig["port"]);
        if ($redisconfig['redis_pwd']) {
            $redis->auth($redisconfig['redis_pwd']);
        }
        if($redisconfig['redis_selectdb'] > 0){
            $redis->select($redisconfig['redis_selectdb']);
        }
        $check = $redis->exists($key);
        if ($check) {
            $redis->incr($key);
            $count = $redis->get($key);
            if ($count > $apiLimit) {
                return false;
            }
        } else {
            $redis->incr($key);
            $redis->pExpire($key, $apiLimitTime);
        }
        return true;
    }


    /*
     * api 请求日志
     * */
    protected function request_log(){
        //api_request_log
        $modulename     = $this->request->module();
        $controllername = $this->request->controller();
        $actionname     = $this->request->action();

        if(strtolower($actionname) == 'givegifttoyou'){
            return true;
        }

        $data = [
            'uid'   => $this->auth->id,
            'api'   => $modulename.'/'.$controllername.'/'.$actionname,
            'params' => json_encode($this->request->request()),
            'addtime'  => time(),
            'adddatetime'  => date('Y-m-d H:i:s'),
            'ip'   => request()->ip(),
        ];
        $request_id = db('api_request_log')->insertGetId($data);
        defined('API_REQUEST_ID') or define('API_REQUEST_ID', $request_id);

    }

    protected function request_log_update($log_result){
        $actionname     = $this->request->action();
        if(strtolower($actionname) == 'givegifttoyou'){
            return true;
        }

        if(defined('API_REQUEST_ID')) { //记录app正常返回结果
            if(strlen(json_encode($log_result['data'])) > 10000) {
                $log_result['data'] = '数据太多,不记录';
            }
            db('api_request_log')->where('id',API_REQUEST_ID)->update(['result'=>json_encode($log_result)]);
        }
    }


}