<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
* 机器人相关
*/
class Robot extends MY_Controller
{
	public $postData = array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);

	protected $smallBlind = array(50, 100, 200, 500, 1000, 2000, 3000, 5000, 10000, 20000);//小盲
    protected $omahaSmallBlind = [5000, 10000, 50000, 100000, 500000, 1000000];

	function __construct()
	{
		parent::__construct();
		$this->load->helper('cookie');
		$this->load->library('curl');

		$this->env = get_cookie($this->_wenenv);
	}

	/**
	*	机器人列表
	*/
	public function list($smallblind = 50)
	{
		$data = array( 'list' => array(), 'smallBlind' => $this->smallBlind, 'cansitin' => 0 );
		if( $this->env == 1 ){
			$url = $this->config->item('officialUrl');
		}else{
			$url = $this->config->item('localUrl');
			$this->postData['demo'] = 1;
		}

		$this->postData['mod'] = 'Robot';
		$this->postData['act'] = 'getlist';
		$this->postData['smallblind'] = $smallblind;
		$retData = $this->curl->req($url, $this->postData);
		$list = json_decode($retData, TRUE);
		if( is_array($list) && !empty($list) ){
			asort($list);
			//判断机器人能进入场次的数量
			$minMoney = $smallblind * 20;
			$cansitin = 0;
			foreach ($list as $info) {
				if($info['money'] >= $minMoney){
					$cansitin++;
				}
			}
			$data['list'] = $list;
			$data['cansitin'] = $cansitin;
		}
		$data['cur'] = $smallblind;
		$this->load->view('robot/list', $data);
	}


	/**
	*	机器人输赢查询
	*/
	public function earnmoney()
	{
		$data = array( 'list' => array(), 'smallBlind' => $this->smallBlind, 'stime' => '', 'etime' => '' );
		if( $this->env == 1 ){
			$url = $this->config->item('officialUrl');
		}else{
			$url = $this->config->item('localUrl');
			$this->postData['demo'] = 1;
		}

		//时间查询
		if( $stime = get_cookie('robotearnmoney_stime') ){
			$data['stime'] = $stime;
			$this->postData['stime'] = strtotime($stime);
		}
		if( $etime = get_cookie('robotearnmoney_etime') ){
			$data['etime'] = $etime;
			$this->postData['etime'] = strtotime($etime);
		}

        

		$this->postData['mod'] = 'Robot';
		$this->postData['act'] = 'earnmoney';
		$retData = $this->curl->req($url, $this->postData);
		$list = json_decode($retData, TRUE);
		$dateList = $info = $infoOmaha = $dataArr = [];
        $str = $strOmaha = '';
		if( is_array($list) && !empty($list) ){
			foreach ($list as $val) {
			    $tmpDate = date('Y-m-d', $val['rbe_time']);
			    if(!in_array($tmpDate, $dateList)) {
                    array_push($dateList, $tmpDate);
                }

				$earnMoneyArr = json_decode($val['rbe_content'], true);
				$gameid = $val['gameid'];
				if($gameid == 3) {
                    foreach ($this->omahaSmallBlind as $smallb_omaha ) {
                        $infoOmaha[$smallb_omaha][] = $earnMoneyArr[$smallb_omaha] ?? 0;
                    }
                }else {
                    foreach ($this->smallBlind as $smallb ) {
                        $info[$smallb][] = $earnMoneyArr[$smallb] ?? 0;
                    }
                }
			}


			//处理详细地址
			if (!empty($info)) {
				$dataStr = '';
				$dataArr = [];
				$i = 0;
				$str = '';
				foreach ($info as $smallb => $moneyList) {
					$str .= '{';
					$str .= "name:'{$smallb}盲注',";
					$str .= "data:[".implode(',', $moneyList)."]";
					$str .='},';
				}
				$str = rtrim($str, ',');
			}

			//处理奥马哈
			if (!empty($infoOmaha)) {
				foreach ($infoOmaha as $smallb => $moneyList) {
                    $strOmaha .= '{';
                    $strOmaha .= "name:'{$smallb}盲注',";
                    $strOmaha .= "data:[".implode(',', $moneyList)."]";
                    $strOmaha .='},';
				}
                $strOmaha = rtrim($strOmaha, ',');
			}
		}
		$data['dateList'] = $dateList;
		$data['dataStr'] = $str;
		$data['omahaStr'] = $strOmaha;
		$data['list'] = $list;

		$this->load->view('robot/earnmoney', $data);
	}

	/**
	*	批量机器人加钱
	*/
	public function actionmultiRobotmoney()
	{
		$smallBlind = $this->input->post('smallBlind');
		$robotmoney = $this->input->post('robotmoney');
		if ($this->env == 2) {
			$url = $this->config->item('localUrl');
			$postData['demo'] = 1;
		}else{
			$url = $this->config->item('officialUrl');
		}
		$postData = $this->postData;
		$postData['mod'] = 'robot';
		$postData['act'] = 'actionmultiRobotmoney';
		$postData['smallBlind'] = $smallBlind;
		$postData['robotmoney'] = $robotmoney;
		$res = $this->curl->req($url, $postData);
		$data = array('referer' =>'', 'refresh' => true, 'state' => 'success', 'message' => '成功');
		die(json_encode($data));
	}


    /**
     *	在线在玩
     */
    public function onlineearnmoney()
    {
        $data = array('dayList' => [], 'list' => []);

        //时间查询
        $dateArr = array('stime' => strtotime('0:0:1'), 'etime' => strtotime('23:59:59'));

        $blindList = [500, 1000, 2000, 2500, 5000, 10000, 50000, ];
        $texasBlindList = [500, 1000, 2500, 5000, 10000, 50000];
        $omahaBlindList = [2000, 5000, 10000, 50000];
        //获取数据
        $postData = array_merge($dateArr, $this->postData);
        $postData['stime'] = $dateArr['stime'];
        $postData['etime'] = $dateArr['etime'];
        $postData['mod'] = 'Robot';
        $postData['act'] = 'onlineearnmoney';
        if ($this->env == 2) {
            $url = $this->config->item('localUrl');
            $postData['demo'] = 1;
        }else{
            $url = $this->config->item('officialUrl');
        }
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);

        ksort($retData['today']);
        //print_r($retData['today']);
        if( is_array($retData) && !empty($retData) ){
            //统计数据
            $list = [];
            //当前在线在玩数据
            $today = empty($retData['today']) ? [] :$retData['today'];
            foreach ($today as $gameid => $todayVal){
                foreach ($todayVal as $todaytime => $v) {
                    $value = unserialize($v);
                    $total = 0;
                    foreach ($blindList as $blind){
                        $blindKey = 'blind_'.$blind;
                        $val = $value[$blind] ?? 0;
                        $list[$gameid][$blindKey][] = $val;
                        $total += $val;
                    }
                    $list[$gameid]['blind_total'][] = $total;
                }
            }

            //昨天在线在玩数据
            $yesterday = empty($retData['yesterday']) ? [] : $retData['yesterday'];
            foreach ($yesterday as $gameid => $yesterVal){
                foreach ($yesterVal as $yestertime => $v) {
                    $total = 0;
                    $value = unserialize($v);
                    foreach ($blindList as $blind){
                        $blindKey = 'yester_blind_'.$blind;
                        $val = $value[$blind] ?? 0;
                        $list[$gameid][$blindKey][] = $val;
                        $total += $val;
                    }
                    $list[$gameid]['yester_blind_total'][] = $total;
                }
            }

            //7天前在线在玩数据
            $last7day = empty($retData['last7day']) ? [] : $retData['last7day'];
            foreach ($last7day as $gameid => $last7dayVal){
                foreach ($last7dayVal as $last7daytime => $v) {
                    $total = 0;
                    $value = unserialize($v);
                    foreach ($blindList as $blind){
                        $blindKey = 'last7day_blind_'.$blind;
                        $val = $value[$blind] ?? 0;
                        $list[$gameid][$blindKey][] = $val;
                        $total += $val;
                    }
                    $list[$gameid]['last7day_blind_total'][] = $total;
                }
            }

            $str = $yesterStr = $last7dayStr = [];
            foreach ($texasBlindList as $k => $bl){
                $blKey = 'blind_'.$bl;
                $isVisible = $k < 1 ? true : false;
                $str[1] .= $this->getSerialStr($bl.'盲注', $list[1][$blKey]).',';
                $yesterStr[1] .= $this->getSerialStr('昨日'.$bl.'盲注', $list[1]['yester_blind_'.$bl], false).',';
                $last7dayStr[1] .= $this->getSerialStr('7日前'.$bl.'盲注', $list[1]['last7day_blind_'.$bl], false).',';
            }
            $str[1] .= $this->getSerialStr('汇总', $list[1]['blind_total']).',';
            $yesterStr[1] .= $this->getSerialStr('昨日汇总', $list[1]['yester_blind_total']).',';
            $last7dayStr[1] .= $this->getSerialStr('7日前汇总', $list[1]['last7day_blind_total']).',';


            foreach ($omahaBlindList as $ko => $obl){
                $blKey = 'blind_'.$obl;
                $isVisible = $ko < 1 ? true : false;
                $str[3] .= $this->getSerialStr($obl.'盲注', $list[3][$blKey]).',';
                $yesterStr[3] .= $this->getSerialStr('昨日'.$obl.'盲注', $list[3]['yester_blind_'.$obl], false).',';
                $last7dayStr[3] .= $this->getSerialStr('7日前'.$obl.'盲注', $list[3]['last7day_blind_'.$obl], false).',';
            }

            $str[3] .= $this->getSerialStr('汇总', $list[3]['blind_total']).',';
            $yesterStr[3] .= $this->getSerialStr('昨日汇总', $list[3]['yester_blind_total']).',';
            $last7dayStr[3] .= $this->getSerialStr('7日前汇总', $list[3]['last7day_blind_total']).',';

            $data['str'] = $str;
            $data['yesterStr'] = $yesterStr;
            $data['last7dayStr'] = $last7dayStr;
            $data['dayList'] = array_keys($yesterday[1]);
            $data['list'] = $list;
        }
        //print_r($data);
        $this->load->view('robot/onlineearnmoney', $data);
    }


    /**
     * 加载机器人输赢统计页面
     */
    public function loseWin()
    {
        $data['stime'] = date('Y-m-d', strtotime("-1 day"));
        $data['etime'] = date('Y-m-d', strtotime("-1 day"));
        $this->load->view('robot/losewin', $data);
    }

    /**
     * 加载report数据
     * @return string
     */
    public function loseWinData()
    {
        $stime = $this->input->post('stime');
        $etime = $this->input->post('etime');
//        $start = $this->input->post('start');
//        $length = $this->input->post('length');

        //获取数据
        $postData = $this->postData;
        $postData['stime'] = empty($stime) ? '' :  strtotime("$stime 0:0:0");
        $postData['etime'] = empty($etime) ? '' : strtotime("$etime 23:59:59");
        //写入stime和etime，为了导出报表查询
        if(!empty($stime)) {
            $data['stime'] = $stime;
        }
        if(!empty($etime)) {
            $data['etime'] = $etime;
        }

        $postData['mod'] = 'Robot';
        $postData['act'] = 'loseWin';
        if ($this->env == 2) {
            $url = $this->config->item('localUrl');
            $postData['demo'] = 1;
        }else{
            $url = $this->config->item('officialUrl');
        }
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);

        if(empty($retData)) {
            die(json_encode($this->withNodata()));
        }

        $total = 0;
        foreach ($retData['list'] as $k => &$_v) {
            $_v['index'] = $k+1;
            $_v['gameName'] = $this->gameList[$_v['gameid']] ?? $_v['gameid'];
            $_v['fee'] = empty($_v['effective_bet']) ? 0 : round($_v['wincoins']*100.0/$_v['effective_bet'], 1).'%';
            $_v['effective_bet'] = number_format($_v['effective_bet']);
            $_v['wincoins'] = number_format($_v['wincoins']);
            $_v['norobot_num'] = $_v['total_num'] - $_v['record_num'];
            $_v['robot_rate'] = empty($_v['total_num']) ? 0 : round($_v['record_num'] * 100/$_v['total_num'], 2).'%';
            $total++;
        }
        $data['recordsTotal'] = $total;
        $data['recordsFiltered'] = $total;
        $data['data'] = $retData['list'];
        die(json_encode($data));
    }

}

