<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/15
 * Time: 16:56
 */

namespace App\Lib\Biz\Sport;


class WagentProxy
{
    private $token = '';
    private $cacheFile = '';
    private $domain = 'http://sports.bocai108.com';
    private $configs = [];


    public function setCacheFile($file = '')
    {
        if (empty($file)) {
            $file = __DIR__ . DIRECTORY_SEPARATOR . 'token.cache';
        }
        $this->cacheFile = $file;
    }

    public function getCacheFile()
    {
        if (empty($this->cacheFile)) {
            $this->cacheFile = __DIR__ . DIRECTORY_SEPARATOR . 'token.cache';
        }
        return $this->cacheFile;
    }

    //写入本地缓存 注意目录和文件要有与入权根
    public function writeTokenCache($array)
    {
        $ret = file_put_contents($this->cacheFile, json_encode($array, 256));
        if (!$ret) {
            throw  new  \Exception("缓存文件写入失败，请检查文件写入权限", 1005);
        }
        return $ret;
    }

    //读取本地缓存
    public function readTokenCache()
    {
        if (!file_exists($this->cacheFile)) {
            return false;
        }
        $ret = file_get_contents($this->cacheFile);
        if ($ret) {
            return $ret;
        } else {
            return false;
        }
    }

    //请求 url地址get时可以带参数  ,param为post提交的参数数组    isPost是否是post方式提交，默认为get
    function request_post($url = '', $param = '', $isPost = 0)
    {
        if (empty($url)) {
            return false;
        }

        if ($isPost && empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        if (!$isPost && $param) {
            $postUrl = $postUrl . '?' . $param;
        }
        curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        if ($isPost) {
            curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        }
        $data = curl_exec($ch);//运行curl
        curl_close($ch);

        return $data;
    }


    //获取token
    protected function getToken()
    {
        $cacheData = json_decode($this->readTokenCache(), true);
        if ($cacheData && isset($cacheData['ctime']) && isset($cacheData['token']) && isset($cacheData['domain'])) {
            $ctime = intval($cacheData['ctime']);
            $token = $cacheData['token'];
            $domain = $this->domain = $cacheData['domain'];

            if ((time() - $ctime) >= 24 * 60 * 60 - 300) {
                $token = '';
            }

            if ($token) {
                $this->domain = $domain;
                $this->token = $token;
                return $token;
            }
        }
        return false;
    }

    //刷新token值
    public function refreshTokenData($config)
    {
        $name = isset($config['name']) ? $config['name'] : '';
        $key = isset($config['key']) ? $config['key'] : '';
        $secret = isset($config['secret']) ? $config['secret'] : '';
        $domain = isset($config['domain']) ? $config['domain'] : '';

        if (empty($name) || empty($key) || empty($secret) || empty($domain)) {
            throw new  \Exception('require params error!', 1000);
        }

        $url = $domain . '/InApi-index/getToken';
        $tokenTmp = $this->request_post($url, ['wagent_name' => $name, 'wagent_key' => $key, 'wagent_secret' => $secret], 1);

        if ($tokenTmp) {
            $tokenData = json_decode($tokenTmp, true);

            if (isset($tokenData['status']) && $tokenData['status'] == 1 && isset($tokenData['data']['token']) && ($tokenData['data']['token'] != '')) {
                $this->writeTokenCache(['ctime' => time(), 'token' => $tokenData['data']['token'], 'domain' => $domain]);
                $this->token = $tokenData['data']['token'];
                return $tokenData['data']['token'];
            } else {
                return $tokenTmp;
            }
        }
        throw new  \Exception('get Token False', 1001);
    }

    //配置
    public function setConfigs(Array $config)
    {
        $name = isset($config['name']) ? $config['name'] : '';
        $key = isset($config['key']) ? $config['key'] : '';
        $secret = isset($config['secret']) ? $config['secret'] : '';
        $domain = isset($config['domain']) ? $config['domain'] : '';
        $cachefile = isset($config['cachefile']) ? $config['cachefile'] : '';

        if (empty($name) || empty($key) || empty($secret)) {
            throw  new  \Exception('初始化参数错误,name,key,secret不能为空', 1002);
        }

        if (empty($domain)) {
            $domain = $this->domain;
        }

        $this->configs = ['name' => $name, 'key' => $key, 'secret' => $secret, 'domain' => $domain];
        $this->setCacheFile($cachefile);

        return true;
    }

    //生成带验证的请求url
    public function makeUrl(String $route, Array $paraArray, $arrayRet = 0)
    {
        $str = '';
        foreach ($paraArray as $nkey => $val) {
            $str .= "&" . $nkey . '=' . $val;
        }
        $param = base64_encode(substr($str, 1));
        if (empty($this->token)) {
            throw  new  \Exception("token 不能为空!", 1007);
        }

        $Key = md5($param . $this->token);

        if ($arrayRet) {
            return ['url' => $this->domain . $route, 'param' => $param, 'key' => $Key];
        }

        $url = $this->domain . $route . '?params=' . $param . '&Key=' . $Key;

        return $url;
    }

    //初始化操作
    public function Init($config)
    {
        $this->setConfigs($config);
        if ($this->getToken()) {
            return true;
        }

        $this->refreshTokenData($this->configs);
        return true;
    }

    //抽象公共请求方法[一定得带上method参数]
    public function commfun(Array $datas, $isPost = 0)
    {
        if (!isset($datas['method'])) {
            throw  new  \Exception("modthod参数缺失", 1006);
        }
        $arrcomm = ['agent' => $this->configs['name'], 'method' => $datas['method']];
        unset ($datas['method']);
        $urlData = $this->makeUrl('/InApi-index/dobusiness', array_merge($datas, $arrcomm), $isPost);

        if ($isPost) {
            $ret = $this->request_post($urlData['url'], ['params' => $urlData['param'], 'Key' => $urlData['key']], 1);
        } else {
            $ret = $this->request_post($urlData);
        }

        return $ret;
    }

    /////////////////////////////////////以下为具体业务逻辑
    //请在调用以下方法前，调用 Init方法作初始化操作

    //2.1检测账户是否存在
    public function caie($name)
    {
        return $this->commfun(['method' => 'caie', 'username' => $name]);
    }

    //2.2 检测并创建账号
    public function caca($name, $pass)
    {
        return $this->commfun(['method' => 'caca', 'username' => $name, 'password' => $pass]);
    }

    ///2.3用户查询余额
    public function gb($name, $pass)
    {
        return $this->commfun(['method' => 'gb', 'username' => $name, 'password' => $pass]);
    }

    ///2.4用户密码更改  (用post方法提交的例子，注意参数格式)
    public function ua($name, $pass)
    {
        return $this->commfun(['method' => 'ua', 'username' => $name, 'password' => $pass], 1);
    }

    ///2.5 代理转给用户或用户转回代理
    public function ptc($name, $pass, $billno, $credit, $type)
    {
        return $this->commfun(['method' => 'ptc', 'username' => $name, 'password' => $pass, 'billno' => $billno, 'credit' => $credit, 'type' => $type], 1);
    }

    ///2.6  代理转给用户或用户转回代理的转账查询
    public function ctc($name, $pass, $billno, $type)
    {
        return $this->commfun(['method' => 'ctc', 'username' => $name, 'password' => $pass, 'billno' => $billno, 'type' => $type]);
    }

    //2.7 按订单查询转账信息
    public function gct($billno)
    {
        return $this->commfun(['method' => 'gct', 'billno' => $billno]);
    }

    //2.8 用户进入游戏
    public function tg($name, $pass, $gametype = 2, $domain = '', $gamekind = 0, $iframe = '0', $platformname = '', $lang = 'zh')
    {
        return $this->commfun(['method' => 'tg', 'username' => $name, 'password' => $pass, 'gametype' => $gametype, 'domain' => $domain, 'gamekind' => $gamekind, 'iframe' => $iframe, 'platformname' => $platformname, 'lang' => $lang], 1);
    }

    //2.9 用户进入游戏
    public function gr($name, $pass, $datestart, $dateend)
    {
        return $this->commfun(['method' => 'tg', 'username' => $name, 'password' => $pass, 'datestart' => $datestart, 'dateend' => $dateend]);
    }

    // 2.10 获取用户的体育投注数据
    public function gsbrbv($billno, $isjs)
    {
        return $this->commfun(['method' => 'gsbrbv', 'vendorid' => $billno, 'isjs' => $isjs]);
    }

    // 3.1 获取用户当天赚钱排行榜 (30分钟缓存)
    public function todaycr()
    {
        return $this->commfun(['method' => 'todaycr']);
    }


    //...............
}

/**
 * 使用例子
 * // $config = ['name' => 'agentname', 'key' => 'agentkey', 'secret' => 'agentsecret', 'domain' => 'http://sports.bocai108.com', 'cachefile' => '/tmp/t234asfasf212128233333.cache'];
 * $config = ['name' => 'agentname', 'key' => 'agentkey', 'secret' => 'agentsecret'];
 * $proxy = new WagentProxy();
 * $proxy->Init($config);
 * $ret1 = $proxy->ua('onmygod', '123456789');
 *
 * print_r($ret1);
 */