<?php
/**
 * Created by PhpStorm.
 * User: ikeke
 * Date: 2018/12/15
 * Time: 13:13
 */

namespace App\Models;


class Rgame_setting extends BaseModel
{
    protected $table = "rgame_setting";
    public $timestamps = false;

    public function getGame($where='')
    {
        $res = $this->where($where)->first();

        if(!$res)
        {
            return -1;
        }
        else
        {
            return $res;
        }
    }

    public function getGames($where='')
    {
        $res = $this->where('game_type',$where)->first();

        if(!$res)
        {
            return -1;
        }
        else
        {
            return $res;
        }
    }

    function getlist($list = 10, $where = '') {//获取列表
        $data = $this->orderBy('ctime', 'desc');
        if (!empty($where) && is_array($where)) {
            $data = $data->where($where);
        }
        $data = $data->paginate($list);

        if (!$data) {
            return -4010010022; //没有数据
        }
        return $data->toArray();
    }

    function getGameList()
    {
        $data = $this->select('game_type','game_zh','extend','agent_name','user_prefix')->where('isopen',1)->get()->toArray();

        return $data;
    }

    //获取真人游戏基本信息
    protected function GetRgameInfo($where=array()){
        $data = $this->select('game_zh','game_type','extend','agent_name','user_prefix');
        if(!empty($where))$data = $data->where($where);
        $data = $data->get();
        if(!$data || count($data->toArray())<1)return -4010010022; //没有数据
        return $data->toArray();
    }

    //查询可下分
    protected function getBalance($account,$gdata){
        //if (empty($account))Render('',-7030);lcqpgame
        $a = array(
            'status' => -1,
            'game_type' => $gdata['game_type']??'lcqpgame',
            'money' => "0.00",
        );
        if(!is_array($gdata)){
            $gdata = $this->GetRgameInfo(array('game_type'=>$gdata));
            if($gdata<0)return $a;
            $gdata = current($gdata);
        }
        $gdata['s'] = 1;
        $agent = $gdata['agent_name'];
        if(count(explode('_', $account))<2){
            $account = $this->setGameName($gdata['user_prefix'],$account,$gdata['game_type']);
            if($account<0)return $a;
        }
        $betobj = '\\App\\Model\\' .ucfirst($gdata['game_type']) . '_betting_ogrbv';
        $jump_url = $betobj::transferGame($agent,$gdata,$account);
        $arr =  $this->curl_get_content($jump_url);
        $array = json_decode($arr, 1);
        if(isset($array['d']['code']) && $array['d']['code'] == 0)
        {
            $a['status'] = 1;
            $a['money'] = is_float($array['d']['money']) ? (string)$array['d']['money'] : $array['d']['money'];
        }
        return $a;
    }

    //上分1,下分2 lcqpgame
    protected function transferCreditNew($account,$money,$ss,$gdata,$loname='')
    {
        if(!is_array($gdata)){
            $gdata = $this->GetRgameInfo(array('game_type','=',$gdata));
            if($gdata<0)return $a;
            $gdata = current($gdata);
        }
        if(count(explode('_', $account))<2){
            $account = $this->setGameName($gdata['user_prefix'],$account,$gdata['game_type']);
            if($account<0)return $a;
        }
        $gdata['s'] = $ss == 1 ? 2 : 3;
        $agent = $gdata['agent_name'];
        $orderid = $this->getOrderId($agent);

        $og = new \App\Models\Oggame_transfer_record();
        //如果Ky用户存在则直接登录//否则注册后登录
        $jump_url = $this->transferGame($agent,$gdata,$account,$money,$orderid);
        $arr =  $this->curl_get_content($jump_url);
        $str = json_decode($arr,1);
        $data = array(
            'order_no' => $orderid,
            'game_type' => $gdata['game_type'],
            'transfer_type' => $ss,
            'casino_user' => $account,
            'local_user' => empty($loname)?explode('_', $account)[2]:$loname,
            'transfer_money' => $money,
            'sub_time' => time(),
            'exec_time' => time(),
        );
        if ($str['d']['code'] == 0)
        {
            $data['exec_result'] = '[成功]单笔转账成功(手机版)';
            $data['type'] = '5';

            $og->insertRec($data);

            $d['status'] = 1;
            $d['data'] = $data;
            $d['msg'] = '充值成功';

            return $d;
        }
        else
        {
            $data['exec_result'] = '[失败]单笔转账失败(手机版)';
            $data['type'] = '2';

            $og->insertRec($data);

            $d['status'] = -1;
            $d['data'] = $str;
            $d['msg'] = '[失败]单笔转账失败(手机版)';

            return $d;
        }
    }

    //接口地址获取
    protected function transferGame($agent,$data,$account,$money=0,$orderid='',$KindID=0,$time=5)
    {
        $ip= GETIP();
        $s = $data['s'];
        $robj = '\App\Models\Rgame_setting';
        $timestamp = str_pad($robj::getMillisecond(),13,0);//时间戳
        $jdata = json_decode($data['extend'], true);
        $DESKey = $jdata['desKey'];//'139B4CCEF28033C9';
        $lineCode=$jdata['lineCode'];
        $prams = 's='.$s;
        if ($s==0){
            $prams .= '&account='.$account.'&money='.$money.'&orderid='.$orderid.'&ip='.$ip.'&lineCode='.$lineCode.'&KindID='.$KindID;
        }elseif ($s==1 || $s==5 || $s==7 || $s==8){
            $prams .= '&account='.$account;
        }else if($s==2||$s==3){
            if($data['game_type'] == 'lcqpgame' || $data['game_type'] == 'lygame'){
                $prams .= '&account='.$account.'&money='.$money.'&orderid='.$orderid;
            }else{
                $prams .= '&account='.$account.'&orderid='.$orderid.'&money='.$money;
            }
        }else if($s==4){
            $prams .= '&orderid='.$orderid;
        }else if($s==6)
        {
            $startTime =  $timestamp-60*$time*1000;
            $endTime = $timestamp;
            $prams .= '&startTime='.$startTime.'&endTime='.$endTime;
        }
        $params = urlencode($robj::openssl_desEncode($prams,$DESKey));//参数加密字符串
        $key = md5($agent.$timestamp.$jdata['md5key']);

        $param = [
            'agent' => $agent,
            'timestamp' => $timestamp,
            'param' => $params,
            'key' => $key,
        ];

        if ($s == 6)
        {
            $url = $jdata['host2'].'?agent='.$agent.'&timestamp='.$timestamp.'&param='.$params.'&key='.$key;
            return $url;
        }

        $url = $jdata['host1'].'?agent='.$agent.'&timestamp='.$timestamp.'&param='.$params.'&key='.$key;
        return $url;
    }

    //获取接口用户名
    protected function setGameName($upex='',$username='',$type='')
    {
        if(empty($upex))return -50630200702;
        if(empty($username))return -50630200802;
        if(empty($type))return -50630200902;
        
        $user = new \App\Models\Oggame_user();
        $is_user = $user->getUser($username,$type);

        if(empty($is_user->rp_name))
        {
            $str = '';

            if(strlen($username) > 6)
            {
                $str = substr($username, -6);
            }
            else
            {
                $str = $username;
            }

            $strs = $upex.$str.'_'.$this->getLetter();

            return $strs;
        }
        else
        {
            return $is_user->rp_name;
        }
    }

    //获取随机4个英文字母
    protected function getLetter()
    {
        $letter = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
        $str = '';

        for($i = 0; $i < 4; $i++)
        {
            $s = rand(0,25);

            $str .= $letter[$s];
        }

        return $str;
    }

    //参数设置方法
    protected function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return $t2 .  ceil( ($t1 * 1000) );
    }

    protected function openssl_desEncode($str,$key)
    {
        $str = $this->pkcs5_pad(trim($str), 16);
        $encrypt_str = openssl_encrypt($str, 'AES-128-ECB', $key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING);
        return base64_encode($encrypt_str);
    }

    protected function pkcs5_pad($text, $blocksize)
    {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
    
    protected function curlData($url, $data, $methd='POST')
    {
        if($data['dbg'] > 0)
        {
            dump($data);
        }

        unset($data['dbg']);

        $ch = curl_init();
        $timeout = 10;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_POST, $methd);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        return $file_contents;
    }

    protected function is_curl_ready()
    {
        return function_exists('curl_version');
    }
    
    protected function dbglog($msg)
    {
        if (is_string($msg))
        {
            syslog(LOG_DEBUG, $msg);
        }
        else
        {
            syslog(LOG_DEBUG, json_encode($msg));
        }
    }

    function getOrderId($agent){
        list($usec, $sec) = explode(" ", microtime());
        $msec=round($usec*1000);
        return $agent.date("YmdHis").$msec;
    }

    protected function curl_get_content($url, $conn_timeout=7, $timeout=15, $user_agent=null)
    {
        if (!$this->is_curl_ready()) {
            $this->dbglog('PHP CURL MODULE MISSING. INSTALL: apt install php7.1-curl php7.2-curl');
            return null;
        }
        $headers = array(
            "Accept: application/json",
            "Cache-Control: no-cache",
            "Pragma: no-cache",
            "Accept-Charset: utf-8;q=1"
        );
        if ($user_agent === null) {
            $user_agent = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36';
        }
        $headers[] = $user_agent;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // curl_setopt($ch, CURLOPT_POST, $methd);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $conn_timeout);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        $res = curl_exec($ch);

        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err = curl_errno($ch);

        curl_close($ch);

        if (($err) || ($httpcode !== 200)) {
            $this->dbglog($res, 'curl result');
            $this->dbglog(["err"=>$err, "code"=>$httpcode], 'curl error');
            return null;
        }
        return $res;
    }
}