<?php
/**
 *------Create thems Controller------
 *------SCWPHP  Version 1.0.0------
 *------Dev Model Jions------
 *------Create Time 2017-06-23 15:06:45------
 */

namespace App\Api\Controller;

use Biz\Account\AccountManager;
use Biz\Game\GameList;
use Illuminate\Support\Facades\DB;
use App\Api\Model\SystemRed;
use App\Api\Model\LuckyMoney;

/*ini_set('display_errors', 1);
error_reporting(E_ALL);*/

class Nologin extends BaseController {

    private $red;
    private $LuckyMoney;

    function init()
    {
        $this->red = new SystemRed();
        $this->LuckyMoney = new LuckyMoney();
    }

    //线路gen
    function routes() {
        // $res = lm('system_routes','api')->get();
        // if (!$res) {
        //     return -6030001222;
        // }
        $type = $_REQUEST['type'] ?? '';
        if (!$type) Render('', -60004);

        $ret = lm('system_routes_category', 'api')->where('remark', $type)->first(['id']);
        if (!$ret) Render('', -60005);
        $res = lm('system_routes', 'api')->where('cate_id', $ret['id'])->get(['name', 'rdesc', 'ip', 'url']);
        if (!$res) Render('', -60005);
        Render($res, '1', lang()->get('success'));
    }

    /**
     * 试玩用户名获取
     * @auther: ikeke
     * @time: 2018-10-30
     */
    function getTestUsername() {
        $accountManager = new AccountManager();
        $num = $accountManager->getAccountId();
        $name = 'gust' . ($num + 1);

        return $name;
    }

    /**
     * 启动页
     */
    public function startup() {
        $res = lm('setinfo', 'Commons')->where('id', '1111')->first();
        if (isset($res->infocontent)) {
            $res->infocontent = str_replace('white-space:normal;', 'white-space:nowrap;', $res->infocontent);
            $res->infocontent = str_replace('white-space: normal;', 'white-space: nowrap;', $res->infocontent);
        }
        Render($res, '1', lang()->get('success'));
    }

    /**
     * jnd
     */
    public function jndset() {
        $res = lm('setinfo', 'Commons')->where('id', '1113')->first();
        $res = $res->toArray();
        $res['extinfo'] = explode('~', $res['extinfo']);
        if (isset($res->infocontent)) {
            $res->infocontent = str_replace('white-space:normal;', 'white-space:nowrap;', $res->infocontent);
            $res->infocontent = str_replace('white-space: normal;', 'white-space: nowrap;', $res->infocontent);
        }
        Render($res, '1', lang()->get('success'));
    }

    /**
     * 连号、遗漏接口
     */
    public function getHotList() {
        $limit = $_REQUEST['limit'] ?? 50;//二维数组长度
        $gameName = isset($_REQUEST['gameName']) && trim($_REQUEST['gameName']) ? trim($_REQUEST['gameName']) : '';
        $gameList = new GameList();
        $lm = lm($gameName, 'commons');
        if (!$lm) {
            Render('', -3201);//游戏不存在
        }
        $gameArray = $lm->where('status', 2)->orderBy('info_no', 'desc')->select('info_no', 'prizes')->limit($limit)->get();
        if ($gameArray)
            $result = $gameList->getPrizes($gameArray);

        //$limit = count ($result);//二维数组长度
        $width = count($result[0]);//二维数组宽度
        $arr = [];
        $arr=self::calcHotOrCold($result);
//        for ($i = 0; $i < $width; $i++) { //遍历列
//            //遍历二维数组中的每一列，移动数组指针，如果当前数据与下条数据相同，same++;继续
//            //否则，从下一个位置的数据起，返回其和一次出现的index与第一条的index的差作为其遗漏值,
//            $same = 1;//换列时默认求同
//            for ($j = 0; $j < $limit; $j++) {  //遍历行，$j=当前行
//                if ($j === 0)
//                    $same = 1;//如果第一行默认求同
//                //如果行当前值==第一行值且求同
//                if ($result[$j][$i] === $result[0][$i] && $same) {
//                    //if (!isset($arr['same'][$result[$i]])) $arr['same'][$result[$i]] = 1;
//                    $arr['same'][$result[0][$i]] = $j + 1;//统计相同
//                } else {
//                    $same = 0;
//                    if ($j + 1 <= $limit) { //如果下一行数据存在
//                        //如果当$arr['dif'][当前行值]不存在且当前行值不等于第一行值 则设置它的值为当前index+1：
//                        if (!isset($arr['dif'][$result[$j][$i]]) && $result[$j][$i] != $result[0][$i]) {
//                            if ($result[$j][$i])//过虑当前期值为空的情况
//                                $arr['dif'][$result[$j][$i]] = $j;
//                        }
//                    }
//                }
//
//            }
//
//        }

        //Render ([$result, $arr], 1);
        Render($arr, 1);
    }

    /* function getBetTypes($gameName)
     {
         return (new GameList())->getBetTypes ($gameName);

     }*/

    /*
     * 路珠统计
     */
    public function getRoadBead() {
        //--2019-01-16 ---blues
        $time = $_REQUEST['time'] ? $_REQUEST['time'] : date('Y-m-d');
        $game_name = trim($_REQUEST['game_name']) ? trim($_REQUEST['game_name']) : '';
        $rule = lang('Long', 'Api')->get('games')[$game_name]['rule'] ?? '5';
//        $rule = ($_REQUEST['rule'])??'5';
//        $rule = trim ($_REQUEST['rule']) ? trim ($_REQUEST['rule']) : '';
        if (empty($game_name)) {
            Render('', -3201);//游戏为空
        }
        if (empty($rule)) {
            Render('', -3204);//现在规则
        }
        $lm = lm($game_name, 'commons');
        if (empty($lm)) {
            Render('', -3202);//游戏不存在
        }

        $nexttime = date("Y-m-d", strtotime("$time +1 day"));
        $where[] = array('status', '=', '2');
        $where[] = array('time', '>=', $time . ' 05:00:00');
        $where[] = array('time', '<=', $nexttime . ' 05:00:00');
        $data = $lm->where($where)->select('info_no', 'prizes', 'codes', 'open_time', 'extra', 'time')->orderby('id', 'asc')->get();
        if (empty($data)) {
            Render('', -3203);//暂无数据
        }
        $data = $data->toArray();
        if (strpos($game_name, '28') !== false) {
            foreach ($data as $key => $value) {
                $extra = json_decode($value['extra'], true);
                //$data[$key]['codes'] = $extra['one'].','.$extra['two'].','.$extra['three'];
                $data[$key]['codes'] = intval($extra['one']) + intval($extra['two']) + intval($extra['three']); //qtx 2018-12-12
            }
        }

        if (strpos($game_name, 'kuai3') !== false) {
            foreach ($data as $key => $value) {
                $extra =explode(',',trim($value['codes']));
                //$data[$key]['codes'] = $extra['one'].','.$extra['two'].','.$extra['three'];
                $data[$key]['codes'] = array_sum($extra); //---- blues
            }
        }


        $arr = array();

        foreach ($data as $key => $value) {
            $codes = explode(',', trim($value['codes']));
            foreach ($codes as $ke => $val) {
                $num = count($arr[$ke]['size']);
                $numtwo = count($arr[$ke]['singlepair']);
                if ($key > 0) {
                    $prevcodes = explode(',', $data[$key - 1]['codes']);
                    if ($val >= $rule) {
                        if ($prevcodes[$ke] >= $rule) {
                            $arr[$ke]['size'][$num][] = 1;
                        } else {
                            $arr[$ke]['size'][$num + 1][] = 1;
                        }
                    } else {
                        if ($prevcodes[$ke] >= $rule) {
                            $arr[$ke]['size'][$num + 1][] = 0;
                        } else {
                            $arr[$ke]['size'][$num][] = 0;
                        }
                    }
                    if ($val % 2 == 0) {
                        if ($prevcodes[$ke] % 2 == 0) {
                            $arr[$ke]['singlepair'][$numtwo][] = 1;
                        } else {
                            $arr[$ke]['singlepair'][$numtwo + 1][] = 1;
                        }
                    } else {
                        if ($prevcodes[$ke] % 2 == 0) {
                            $arr[$ke]['singlepair'][$numtwo + 1][] = 0;
                        } else {
                            $arr[$ke]['singlepair'][$numtwo][] = 0;
                        }
                    }

                } else {
                    if ($val >= $rule) {
                        $arr[$ke]['size'][1][] = 1;
                    } else {
                        $arr[$ke]['size'][1][] = 0;
                    }
                    if ($val % 2 == 0) {
                        $arr[$ke]['singlepair'][1][] = 1;
                    } else {
                        $arr[$ke]['singlepair'][1][] = 0;
                    }
                }

            }

        }

        Render($arr, 1);
    }

    public function resultAnalysis() {
        $limit = $_REQUEST['limit'] ?? 100;//二维数组长度
        $gameName = isset($_REQUEST['gameName']) && trim($_REQUEST['gameName']) ? trim($_REQUEST['gameName']) : '';
        return ($return = $this->calc($gameName, $limit));
    }


    /**
     * 冷热遗漏数据计算函数
     * @param $gameName
     * @param int $limit
     * @return mixed
     */
    private function calc($gameName, $limit = 100) {
        $gameList = new GameList();
        $lm = lm($gameName, 'commons');
        if (!$lm) {
            Render('', -3201);//游戏不存在
        }
        $gameArray = $lm->where('status', 2)->orderBy('info_no', 'desc')->select('info_no', 'prizes')->limit($limit)->get();
        if ($gameArray)
            $result = $gameList->getPrizes($gameArray);
        $count = count($result);//数组长度
        $width = count($result[0]);//数组宽度
        $hots = [];
        $colds = [];
        for ($i = 0; $i < $width; $i++) { //$i=>列ID
            $ret = [];//当前列的所有元素
            for ($j = 0; $j < $count; $j++) { //$j=>行ID
                //取回各列元素数组
                array_push($ret, $result[$j][$i]);
            }
            //热号统计：
            //遍历结果集每一列的每一个元素，统计其出现的频次(取回每列的值ARR，通过array_count_values函数统计)
            $hots = array_merge($hots, array_count_values($ret));
            //
            $colds = array_merge($colds, $this->getCold($ret));
        }
        $return['hots'] = $hots;
        $return['colds'] = $colds;
        return $return;
    }

    /**
     * 遗漏计算子函数
     * @param $arr
     * @return array
     */
    private function getCold($arr) {
        $ret = [];
        foreach ($arr as $k => $v) {
            //遍历每一个元素
            if (!isset($ret[$v]))
                $ret[$v] = (function ($k) use ($arr) {
                    $num = 0;
                    //reset ($arr);
                    if ($arr[0] === $arr[$k]) return 0;
                    while ($arr[$num] !== $arr[$k]) {
                        $num++;
                    }
                    return $num;

                })($k);
        }
        //dd($ret);
        return $ret;
    }

    /**
     *统计游戏冷热遗漏接口
     *
     */
    public function getGameAnalysis() {
        $game_code = $_REQUEST['gameName'];
        if (!$game_code) {
            Render('', -3264);//游戏名不能为空
        }
        $limit = $_REQUEST['limit'] ?? 100;
        $currentGame = lm($game_code, 'commons')->whereNotNull('prizes')->orderBy('info_no', 'desc')->select('info_no')->first();
        //currentGame=>游戏当前开奖数据
        if (!$currentGame) {
            //无当前游戏开奖数据
            Render('', -3266);
        }
        $current_issue = $currentGame->info_no;
        $lm = lm('GameAnalysis', 'commons');
        $currentData = $lm->where('game_code', $game_code)->first();//分析数据
        if ($currentData && $current_issue == $currentData->current_issue) {
            $ret = [
                'hots' => json_decode($currentData->hot_list),
                'colds' => json_decode($currentData->cold_list),
                'issue' => $current_issue
            ];
        } else {
            //重新请求计算
            $calc = $this->calc($game_code, $limit);
            if (!$calc) {
                Render('', -51028);//统计数据不存在
            }
            $hots = json_encode($calc['hots']);
            $colds = json_encode($calc['colds']);
            if (!$currentData) {
                $lm->insert(['game_code' => $game_code, 'hot_list' => $hots, 'cold_list' => $colds, 'current_issue' => $current_issue]);
            } else {
                $lm->where('game_code', $game_code)
                    ->update(['game_code' => $game_code, 'hot_list' => $hots, 'cold_list' => $colds, 'current_issue' => $current_issue]);
            }
            $ret = ['hots' => $calc['hots'], 'colds' => $calc['colds'], 'issue' => $current_issue];
        }
        Render($ret, 1);
    }

    // todo 这个为临时工具代码 不上线 可删
    public function toJson() {
        $game_code = $_REQUEST['gameName'];
        $ret = $this->calc($game_code, 200);
        $hots = $ret['hots'];
        $arr = [];
        $group = [];
        $childs = [];
        foreach ($hots as $v => $k) {
            //$v=>玩法名称
            //$vv[0]=>分类
            //$name=>分类下分组名称
            $vv = explode('-', $v);
            $vvv = explode('_', $vv[1] ?? $vv[0]);
            $name = count($vvv) === 2 ? $vv[0] . '-' . $vvv[0] : $vv[0];
            $group[$vv[0]][$name] = [
                'name' => $name,//当前组的名称
                'title' => $this->getTitle($game_code, $name),//当前组的中文名称
                'desc' => ''
            ];
            $childs[$vv[0]][$name][$v] = $this->getChild($game_code, $v);
            ksort($childs[$vv[0]][$name]);
            $group[$vv[0]][$name]['childs'] = array_values($childs[$vv[0]][$name]);
            $arr['root'][$vv[0]] = [
                'name' => $vv[0],
                'title' => $this->getTitle($game_code, $vv[0]),
                'extra' => null,
                'group' => array_values($group[$vv[0]])
            ];

        }
        foreach ($arr['root'] as $k => $v) {

            ksort($arr['root'][$k]['group']);
        }
        $arr['root'] = array_values($arr['root']);
        return ([$arr]);
    }

    // todo 这个为临时工具代码 不上线 可删
    public function gameExplain() {
        $game_code = $_REQUEST['gameName'];
        $ret = $this->calc($game_code, 200);
        $hots = $ret['hots'];
        $arr = [];
        $group = [];
        $childs = [];
        foreach ($hots as $v => $k) {
            //$v=>玩法名称
            //$vv[0]=>分类
            //$name=>分类下分组名称
            $vv = explode('-', $v);
            $vvv = explode('_', $vv[1] ?? $vv[0]);
            $name = count($vvv) === 2 ? $vv[0] . '-' . $vvv[0] : $vv[0];
            $group[$vv[0]][$name] = [
                'name' => $name,//当前组的名称
                'title' => $this->getTitle($game_code, $name),//当前组的中文名称
                'desc' => ''
            ];
            $childs[$vv[0]][$name][$v] = $this->getChild($game_code, $v);
            ksort($childs[$vv[0]][$name]);
            $group[$vv[0]][$name]['childs'] = array_values($childs[$vv[0]][$name]);
            $arr['root'][$vv[0]] = [
                'name' => $vv[0],
                'title' => $this->getTitle($game_code, $vv[0]),
                'extra' => null,
                'group' => array_values($group[$vv[0]])
            ];

        }
        foreach ($arr['root'] as $k => $v) {

            ksort($arr['root'][$k]['group']);
        }
        echo $str = $game_code . PHP_EOL . PHP_EOL;
        file_put_contents("./gameExplain.cvs", $str);
        foreach ($arr["root"] as $a => $x) {
            if (count($x["group"]) == 1) {
                echo $str = $x["title"] . "," . $x["name"] . PHP_EOL;
                file_put_contents("./gameExplain.cvs", $str, FILE_APPEND);
            } else {
                foreach ($x["group"] as $b) {
                    $b["title"] = !empty($b["title"]) ? $b["title"] : $x["title"];
                    echo $str = $b["title"] . "," . $b["name"] . PHP_EOL;
                    file_put_contents("./gameExplain.cvs", $str, FILE_APPEND);
                }
            }

        }
        // $arr['root'] = array_values ($arr['root']);
        // return (1);

    }

    private function getTitle($game_name, $name) {
        $name = lang($game_name)->get($name);
        return $name;
    }

    private function getChild($game_name, $name) {
        return $data = [
            'name' => $name,
//            'title' => $this->getTitle ($game_name, $name),
            'title' => '',
            'align' => 1
        ];
    }

    //注册设置
    public function getSettings() {
        $settings = lm('settings', 'commons')->where('id', 1)->first();
        if (!empty($settings)) {
            $settings = $settings->toArray();
        }
        return $settings;
    }

    /**
     * 头像列表
     * @return mixed
     */
    public function getFaces() {
        $list = file_get_contents(ROOT_PATH . '/Config/faces.json');
        Render(json_decode($list), 1);
    }

    //根据域名获取代理用户邀请码
    public function getInviteByDom() {
        $dom = isset($_REQUEST['dom']) ? $_REQUEST['dom'] : '';
        if (!$dom) {
            Render('', -41101, '参数错误');
        }
        $res = lm('nagent_detailed', 'commons')->select('invite')->where('domain_name','like','%'.$dom.'%')->first();
        if (!$res) {
            Render('', -41101, '代理不存在');
        }
        $data = $res->toArray();
        Render($data, 1, '成功');
    }

    public function room_conf() {
        $sStr = lm('Setinfo', 'commons')->getSensitive()->infocontent ?? '';
        $wlStr = lm('Setinfo', 'commons')->getWhiteList()->infocontent ?? '';
        $data = [
            "info_t" => $wlStr,
            "in_status" => "1",
            'word_info' => $sStr,
            "word_status" => "1"
        ];
        return ($data);
    }

    /**自动拉取流水记录**/
    public function automaticPullData()
    {
        $gametype = $_GET['gametype'];

        if($gametype === 'oggame')
        {
            $og = new \App\Egame\Controller\OgGame();

            $lastdata = lm('oggame_betting_ogrbv','commons')->orderBy('id','desc')->first();

            $data = $og->getBettingRecordByVendorNew($lastdata->VendorId);

            $userobj = new \App\Commons\Model\Oggame_user();

            foreach($data['data'] as $key => $val)
            {
                $iscf = lm('oggame_betting_ogrbv','commons')->where('VendorId', $val['VendorId'])->first();

                if(empty($iscf->VendorId))
                {
                    $user = $userobj->getRpUser($val['UserName'], 'oggame');

                    $data['data'][$key]['AddTime'] = strtotime(str_replace('/','-',$val['AddTime']));

                    if(!empty($user->lo_name))
                    {
                        $uid = lm('account','commons')->where('', $user->lo_name)->first();

                        $data['data'][$key]['account_name'] = $uid->account;
                        $data['data'][$key]['account_identity'] = $uid->identity;
                    }
                    else
                    {
                        $data['data'][$key]['account_name'] = '';
                        $data['data'][$key]['account_identity'] = '';
                    }
                }

                lm('oggame_betting_ogrbv','commons')->insert($data['data'][$key]);
            }

            render('',1,'数据拉取成功');
        }
        else if($gametype === 'kygame')
        {
            $ky = new \App\Egame\Controller\KyGame();

            $data = $ky->getBettingRecordByVendorNew();

            if($data['status'] == -1)
            {
                render('',-1,'暂无可拉取的数据');
            }
            else if($data['status'] == -2)
            {
                render('',-1,'接口异常，请稍后再试');
            }
            else if($data['status'] == 1)
            {
                $userobj = new \App\Commons\Model\Oggame_user();

                $arr = array();
                foreach($data['data']['d']['list'] as $key => $val)
                {
                    for($i = 0; $i < $data['data']['d']['count']; $i++)
                    {
                        $arr[$i][$key] = $val[$i];
                    }
                }

                foreach($arr as $ak => $al)
                {
                    $is = lm('kygame_betting_ogrbv','commons')->where('GameID', $al['GameID'])->first();

                    if(empty($is->GameID))
                    {
                        $user = $userobj->getRpUser($al['Accounts'], 'kygame');

                        if(!empty($user->lo_name))
                        {
                            $uid = lm('account','commons')->where('', $user->lo_name)->first();

                            $al['account_name'] = $uid->account;
                            $al['account_identity'] = $uid->identity;
                        }
                        else
                        {
                            $al['account_name'] = '';
                            $al['account_identity'] = '';
                        }
                    }

                    lm('kygame_betting_ogrbv','commons')->insert($al);
                }

                render('',1,'数据拉取成功');
            }
            else
            {
                render('',-1,'接口异常，请稍后再试');
            }
        }
        else
        {
            render('',-1,'游戏类型错误');
        }
    }

    /**
     * 用户所有游戏或单个游戏有效投注总额
     * @param $account_identity
     * @param string $starttime
     * @param string $endtime
     * @param string $gametype
     * @return int 返回真人流水
     */
    public function totalUserStatistics($account_identity, $starttime = '', $endtime = '', $gametype = 'all'): int
    {
        $starttime = $starttime ? $starttime : '' . date('Y-m-d 00:00:00', time()) . '';
        $endtime = $endtime ? $endtime : '' . date('Y-m-d 23:59:59', time()) . '';

     if(empty($account_identity))
        {
            return -1;
        }
        else
        {
            $rgame_setting = new \App\Commons\Model\Rgame_setting();
            $whererg['isopen'] = 1;
            $rgamelist = $rgame_setting->getGameList($whererg);
//            var_dump($rgamelist);exit;
            $ogobj = new \App\Commons\Model\Oggame_betting_ogrbv();
            $kyobj = new \App\Commons\Model\Kygame_betting_ogrbv();
            $agobj = new \App\Commons\Model\Aggame_betting_ogrbv();
            $hjobj = new \App\Commons\Model\Hjgame_betting_ogrbv();
            $lcqpobj = new \App\Commons\Model\Lcqpgame_betting_ogrbv();
            $lyobj = new \App\Commons\Model\Lygame_betting_ogrbv();

            $om =  $km= 0;
            if($gametype == 'all')
            {
                $where = array();
                $where[] = array('account_identity','=', $account_identity);
                $ogwhere[] = array('AddTime','>=', strtotime($starttime));
                $ogwhere[] = array('AddTime','<=', strtotime($endtime));

                $om = $ogobj->getUserMoney($where,$ogwhere);
                
                $kywhere[] = array('GameEndTime','>=', strtotime($starttime));
                $kywhere[] = array('GameEndTime','<=', strtotime($endtime));

                $km = $kyobj->getUserMoney($where, $kywhere);

                $agwhere[] = array('betTime','>=', strtotime($starttime));
                $agwhere[] = array('betTime','<=', strtotime($endtime));
                $ag = $agobj->getUserMoney($where, $agwhere);

                $hjwhere[] = array('bet_time','>=', strtotime($starttime));
                $hjwhere[] = array('bet_time','<=', strtotime($endtime));
                $hj = $hjobj->getUserMoney($where, $hjwhere);

                $lcqpwhere[] = array('GameEndTime','>=', strtotime($starttime));
                $lcqpwhere[] = array('GameEndTime','<=', strtotime($endtime));
                $lcqp = $lcqpobj->getUserMoney($where, $lcqpwhere);

                $lywhere[] = array('GameEndTime','>=', strtotime($starttime));
                $lywhere[] = array('GameEndTime','<=', strtotime($endtime));
                $ly = $lyobj->getUserMoney($where, $lywhere);

            }

            return   $om + $km + $ag + $hj + $lcqp + $ly;
        }
    }

    //系统红包生成，用于服务器定时请求,不对前台开放 2019-01-22 anton
    public function createSystemRed()
    {
        $user = $_REQUEST['user'];
        $time = $_REQUEST['time'];
        $sign = $_REQUEST['sign'];
        if(empty($user))
        {
            echo lang('SystemRed')->get('admin_error');
            exit;
        }
        if(empty($sign))
        {
            echo lang('SystemRed')->get('sign_error');
            exit;
        }
        $token  = lm('Setinfo', 'commons')->where('id',1007)->first();
        if(empty($token->infocontent))
        {
            echo lang('SystemRed')->get('token_error');
            exit;
        }
        if($this->sign($user,$time,$token->infocontent,$sign))
        {
            $time = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','00'];
            $curt = date('H',time());
            $start = date('Y-m-d H',time()).':00:00';
            $end = date('Y-m-d H',time()).':59:59';
            foreach ($time as $t)
            {
               if($curt == $t)
               {
                   $where['start'] = $start;
                   $where['end'] = $end;
                   $res = $this->LuckyMoney->checkRed($where);
                   if(!count($res))
                   {
                       _beginTransaction();
                       $redinfo = $this->red->getRedInfo();
                       if (count($redinfo) == 0) {
                           echo lang('SystemRed')->get('red_error');
                           exit;
                       }
                       $redinfo = $redinfo->toArray();
                       foreach ($redinfo as $k => $v)
                       {
                           //获取用户金额
                           $uinfo = lm('account', 'Commons')
                               ->leftjoin('account_detailed', 'account_detailed.account_identity', '=', 'account.identity')
                               ->select('account.identity', 'account_detailed.cash','account.account')
                               ->where('account.account', '=', $v['username'])
                               ->first();
                           if (count($uinfo) == 0) {
                               echo $v['username'] . lang('SystemRed')->get('account_error');
                               exit;
                           }
                           $uinfo = $uinfo->toArray();
                           if (floatval($v['red_money']) > floatval($uinfo['cash'])) {
                               echo $v['username'] . lang('SystemRed')->get('money_error');
                               exit;
                           }
                           try {
                               $roomid = intval($v['room_id']);
                               $money = floatval($v['red_money']);
                               $nos = intval($v['red_num']);
                               $message = trim($v['red_mark']);
                               $type = 3;
                               $luck = $this->LuckyMoney->handleLuckyMoney($uinfo['identity'], $money, $nos, $roomid, $type, $message, function ($redid, float $money, int $nos, int $type) {

                                   $redList = $this->redBag($money, $nos); //生成红包数据
                                   $in_data = [];
                                   foreach ($redList as $d) {
                                       $in_data[] = ['redid' => $redid, 'money' => $d, 'created_at' => date('Y-m-d H:i:s')];
                                   }
                                   lm('Chat_redbag', 'Api')->insert($in_data);
                                   return 1;
                               });
                               if(intval($luck) < 0){
                                   Render('', $luck);
                               }else{
                                   $redData[$k]['data']['data']['lm_id'] = $luck;
                                   $redData[$k]['data']['type'] = 203;
                                   $redData[$k]['data']['time'] = (int)time();
                                   $redData[$k]['data']['data']['room_id'] = $roomid;
                                   $redData[$k]['data']['data']['money'] = $money;
                                   $redData[$k]['data']['data']['type'] = 3;
                                   $redData[$k]['data']['data']['data'] = $message;
                                   $redData[$k]['type'] = 203;
                                   $redData[$k]['has_take'] = 0;
                                   $redData[$k]['time'] = (int)time();
                               }
                               _commit();
                           } catch (\Exception $e) {
                               _rollback();
                               Render('', -7045);
                           }
                       }
                       $this->SendMesage($redData);
                   }else{
                       echo lang('SystemRed')->get('send_red');
                       break;
                   }
               }else{
                    continue;
               }
            }
        }else{
            echo lang('SystemRed')->get('sign_error');
            exit;
        }
    }

    //红包数据生成
    function redBag($money, int $piece, $min = 1)
    {
        srand(time());
        $list = [];
        $count = 0;
        while ($piece > 1) {
            $curr = rand($min, $money * 100 / $piece * 1.5);
            $money -= $curr / 100;
            $list[] = (float)number_format($curr / 100, 2, '.', '');
            $count += $curr / 100;
            $piece--;
        }
        $list[] = (float)number_format($money, 2, '.', '');
        $count += $money;
        return $list;
    }

    //推送红包数据
    public function SendMesage($redData)
    {
        $wsport = lm('Setinfo', 'commons')->getInfo(9501);
        $server = $wsport[0]['infocontent'];
        $server = !empty($server) ? explode('||', $server) : '';
        $server = !empty($server[0]) ? explode(':', $server[0]) : '';

        if (empty($server[1])) {
             echo lang('SystemRed')->get('server_error');
             return false;
        }
        $server = count($server) > 2 ? $server[1] . ':' . $server[2] : $server[1];
        $postUrls = $server . '/' . 'srpkg';
        $sendData = [
            'sign' => md5(time() . $wsport[0]['extinfo']),
            'time' => (int)time(),
            'redData' => json_encode($redData)
        ];
        $chs = curl_init();//初始化curl
        curl_setopt($chs, CURLOPT_URL, $postUrls);//抓取指定网页
        curl_setopt($chs, CURLOPT_HEADER, 0);//设置header
        curl_setopt($chs, CURLOPT_TIMEOUT, 15);
        curl_setopt($chs, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($chs, CURLOPT_POST, 1);//post提交方式
        curl_setopt($chs, CURLOPT_POSTFIELDS, $sendData);
        curl_exec($chs);//运行curl
        if (curl_errno($chs) != 0) {
            $status = curl_errno($chs);
            $msg = lang('SystemRed')->get('server_error');
        } else {
            $status = 1;
            $msg = lang('SystemRed')->get('success');
        }
        curl_close($chs);
        echo lang('SystemRed')->get('sendtime'). date('Y-m-d H:i:s', time()) . ','.lang('SystemRed')->get('status') . $status . ','.lang('SystemRed')->get('msg') . $msg;
    }

    protected function calcHotOrCold($data) {
        $xy28=['specialthree'];
        $ssc=['fronttwostar','frontthreestar','behindthreestar','fourstar','fivestar'];
        $lhc=['series','selfselect','general_pass','join_born'];
        $pk10=['head_two','head_three'];
        $k3=['thdiffnum','trnumro','tsnum','tsnumro','twodiffnum'];
        $arr=array_merge($xy28,$ssc,$pk10,$k3,$lhc);
        $pattern='/'.implode('|',$arr).'/';
        $hot=[];
        $cold=[];
        $count=count($data);
        foreach($data as $k=>$v){
            foreach($v as $kk=>$vv){
                $skip=preg_match($pattern,$vv);
                if($skip)continue;
                if($k===0)$hot[$vv]=1;
                $hot[$vv]++;
            }
        }
        foreach ($hot as $k=>$v){
            $cold[$k]=$count-$v;
        }
        return['same'=>$hot,'dif'=>$cold];
    }

    //签名验证
    protected function sign($user,$time,$token,$sign)
    {
        if(isset($time) && $time !=0) //时间存在
        {
            if(time()-intval($time) < 60) //小于一分钟
            {
                $str = 'user='.$user.'&time='.$time.'&token='.$token;
                $md5 = md5($str);
                if($md5 == $sign)
                {
                    return true;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            $str = 'user='.$user.'&token='.$token;
            $md5 = md5($str);
            if($md5 == $sign)
            {
                return true;
            }else{
                return false;
            }
        }
    }

    /**
     * 子游戏列表
     */
    public function getSubGameLists()
    {
        $child_type = isset($_REQUEST['child_type']) ? $_REQUEST['child_type'] : '';
        $is_page = isset($_REQUEST['is_page']) ? $_REQUEST['is_page'] : 0;
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;
        $limit = isset($_REQUEST['limit']) ? $_REQUEST['limit'] : 10;

        if(empty($child_type))
        {
            render('', -1, '请传入子游戏类型');
        }
        else
        {
            $subgame = array();
            $where[] = array('parent_id','>', 0);
            //不需要分页
            if($is_page == 0)
            {
                $subgame = lm('rgame_subclass','commons')
                    ->where('sub_type', $child_type)
                    ->where('status', 1)
                    ->where($where)
                    ->select('id','sname_en','icon','sname_zh','game_type','recommend','sub_type','child_name','order','parent_id','cate_id','status','extend','corner')
                    ->orderBy('order','desc')
                    ->get();
            }
            //需要分页
            else if($is_page == 1)
            {
                $count = lm('rgame_subclass','commons')
                    ->where('sub_type', $child_type)
                    ->where('status', 1)
                    ->where($where)
                    ->count();

                $count_page = ceil($count / $limit);

                if($page > $count_page)
                {
                    render('', -1, '没有更多数据了');
                }

                $first = ($page - 1) * $limit;

                $subgame = lm('rgame_subclass','commons')
                    ->where('sub_type', $child_type)
                    ->where('status', 1)
                    ->where($where)
                    ->select('id','sname_en','icon','sname_zh','game_type','recommend','sub_type','child_name','order','parent_id','cate_id','status','extend','corner')
                    ->offset($first)->limit($limit)->orderBy('order','desc')->get();
            }
            else
            {
                render('', -1, '分页开关值错误');
            }

            if(count($subgame) > 0)
            {
                $arr = $subgame->toArray();
                foreach($arr as $key => $val)
                {
                    $arr[$key]['icon'] = '/Public/themes/default/static/gamesimg/'.$val['game_type'].'/'.$val['icon'];
                }

                render($arr, 1, '子游戏列表获取成功');
            }
            else
            {
                render('', -1, '子游戏类型错误');
            }
        }
    }
}
