<?php

declare (strict_types = 1);

namespace app\handle\controller;
use app\models\process\Boot;
use app\models\process\NumberTab;
use app\models\table\Table;
use app\models\table\UserController;
use freedom\utils\CardPositionNn;
use freedom\utils\Waybill;
use think\facade\Env;
use think\facade\Session;
use think\facade\Request;
use think\facade\Lang;
use think\facade\View;
use think\response\Redirect;
use think\response\Json;

class Index extends Common{
	public function index(): Redirect
    {
		$find = Session::get('user_info');
		$tableInfo = Table::get($find['table_id']);
		if($tableInfo['game_id'] == 2){
            $template = $tableInfo['scanner_type'] == 2 ? '/index/tab_dt_sb' : '/index/tab_dt';
			return redirect($template);

		}else if($tableInfo['game_id'] == 4){
            $template = $tableInfo['scanner_type'] == 2 ? '/index/tab_nn_sb' : '/index/tab_nn';
			return redirect($template);

		}else if($tableInfo['game_id'] == 5){
			return redirect('/index/tab_knn');
		}else if($tableInfo['game_id'] == 1){
            $template = $tableInfo['scanner_type'] == 2 ? '/index/tab_baccarat_sb' : '/index/tab_baccarat';
			return redirect($template);

		}else if($tableInfo['game_id'] == 6){
            return redirect('/index/tab_toning');
        }else if($tableInfo['game_id'] == 7){
            return redirect('/index/tab_dice');
        }else{
			return redirect('/login/logout');
		}
    }
    private static function precondition(){
	    $userInfo = Session::get('user_info');
	    $userController = UserController::get($userInfo['id']);
	    $loginToken = create_login_token($userController);
	    UserController::where(['id' => $userController['id']])->update(['login_token' => $loginToken]);
        $tableInfo = Table::get($userController['table_id']);
        $langType = cookie('think_lang');

        // 渲染参数和模板
        View::assign('login_token',$loginToken);
        View::assign('table',$tableInfo);
        View::assign('user',$userController);
        View::assign('langType',$langType);
        View::assign('websocketUrl',Env::get('system.WEBSOCKET'));
        View::assign('websocketProtocol',Env::get('system.PROTOCOL'));
        View::assign('logoPath',Env::get('system.LOGO_PATH'));
        View::assign('player',Env::get('system.PLAYER'));

        //View::assign('localSbServer',Env::get('system.SB_SERVER'));
        View::assign('localSbServer', $tableInfo['media_near_rtmp']); // 无用的字段来作为本地识别设备IP
    }
    function get_lang(): Json
    {
	    if (!Request::instance()->isPost()) return json();
        $lang = Lang::get();
        return json(['status' => 1, 'lang' => $lang]);
    }
	public function tab_baccarat(): string
    {
		self::precondition();
        $find = Session::get('user_info');
        $tableInfo = Table::get($find['table_id']);
        if($tableInfo['is_scavenging'] == 1){
            return View::fetch('/index/tab_b_auto');
        }else{
            return View::fetch('/index/tab_b');
        }


	}
    public function tab_baccarat_sb(): string
    {
		self::precondition();
        return View::fetch('/index/tab_b_sb');		
	}

	public function tab_dt(): string
    {
        self::precondition();
        $find = Session::get('user_info');
        $tableInfo = Table::get($find['table_id']);
        if($tableInfo['is_scavenging'] == 1){
            return View::fetch('/index/tab_dt_auto');
        }else{
            return View::fetch('/index/tab_dt');
        }

	}
    public function tab_dt_sb(): string
    {
		self::precondition();
        return View::fetch('/index/tab_dt_sb');		
	}

	public function tab_nn(): string
    {
		self::precondition();
		return View::fetch('/index/tab_nn');
	}
    public function tab_nn_sb(): string
    {
		self::precondition();
		return View::fetch('/index/tab_nn_sb');
	}
	public function tab_knn(): string
    {
		self::precondition();
		return View::fetch('/index/tab_knn');
	}
    public function tab_toning(): string
    {
        self::precondition();
        return View::fetch('/index/tab_toning');
    }
    public function tab_dice(): string
    {
        self::precondition();
        return View::fetch('/index/tab_dice');
    }

    public function tab_roulette(): string
    {
        self::precondition();
        return View::fetch('/index/tab_roulette');
    }
	//获取当前靴的结果汇总
	public function get_boot(): Json
    {
        if (!Request::instance()->isPost()) return json();
        $bootId = intval(Request::instance()->post('boot_id'));
        $bootInfo = Boot::get($bootId);
        return json(['code'=>1,'data'=>$bootInfo]);
	}

	// 路单接口调用
	public function waybill(): Json
    {
        if (!Request::instance()->isPost()) return json();
        // 接收游戏ID和靴ID
        $bootId = intval(Request::instance()->post('boot_id'));
        $forecast = intval(Request::instance()->post('forecast'));
        // 验证靴ID
        if($bootId > 0){
            $ns = NumberTab::getByBootIdDone($bootId,'result,pair');
            if($forecast == 1){
                // 庄问路
                $ns[] = array('result'=>1,'pair'=>0);
            }elseif($forecast == 2){
                // 闲问路
                $ns[] = array('result'=>2,'pair'=>0);
            }
            // 数据存在，输出路单
            if($ns){
                $result = Waybill::waybill($ns);
                return json($result);
            }else{
                $waybill = array();
                $waybill['bigEyeRoad'] = [];
                $waybill['bigRoad'] = [];
                $waybill['pathway'] = [];
                $waybill['roach'] = [];
                $waybill['showRoad'] = [];
                return json(['status'=>false,'waybill'=>$waybill]);
            }
        }else{
            return json(['status'=>false,'msg'=>'靴ID错误']);
        }
	}
	// 路单接口调用
	public function waybill_nn(): Json
    {
        if (!Request::instance()->isPost()) return json();
        $bootId = intval(Request::instance()->post('boot_id'));
        // 验证靴ID
        if($bootId > 0){
            $ns = NumberTab::getByBootIdDone($bootId,'result_banker,result_player_1,result_player_2,result_player_3,win_player_1,win_player_2,win_player_3');
            if($ns){
                $result = Waybill::waybillNn($ns);
                return json($result);
            }else{
                $waybill = array();
                return json(['status'=>false,'msg'=>'数据不存在','waybill'=>$waybill]);
            }
        }else{
            return json(['status'=>false,'msg'=>'靴ID错误']);
        }
	}
    // 色碟露珠
    public function waybill_toning(){
        if (!Request::instance()->isPost()) return json();
        $bootId = intval(Request::instance()->post('boot_id'));
        // 验证靴ID
        if($bootId > 0){
            $ns = NumberTab::getByBootIdDone($bootId,'toning_result');
            if($ns){
                $result = Waybill::waybillToning($ns);
                return json($result);
            }else{
                $waybill = array();
                return json(['status'=>false,'msg'=>'数据不存在','waybill'=>$waybill]);
            }
        }else{
            return json(['status'=>false,'msg'=>'靴ID错误']);
        }
    }

    public function waybill_dice(){
        if (!Request::instance()->isPost()) return json();
        $bootId = intval(Request::instance()->post('boot_id'));
        // 验证靴ID
        if($bootId > 0){
            $ns = NumberTab::getByBootIdDone($bootId,'dice_result');
            $waybill = array();
            if($ns){
                foreach ($ns as $v){
                    $strArray = explode(",", $v['dice_result']);
                    $intArray = array();
                    foreach ($strArray as $value){
                        $intArray[] = intval($value);
                    }
                    $waybill[] = $intArray;
                }
                return json(['status'=>true,'msg'=>'数据存在','waybill'=>$waybill]);
            }else{
                return json(['status'=>false,'msg'=>'数据不存在','waybill'=>$waybill]);
            }
        }else{
            return json(['status'=>false,'msg'=>'靴ID错误']);
        }
    }
    // 轮盘露珠
    // 色碟露珠
    public function waybill_roulette(){
        if (!Request::instance()->isPost()) return json();
        $bootId = intval(Request::instance()->post('boot_id'));
        // 验证靴ID
        if($bootId > 0){
            $ns = NumberTab::getByBootIdDone($bootId,'roulette_result');
            if($ns){
                $result = Waybill::waybillRoulette($ns);
                return json($result);
            }else{
                $waybill = array();
                return json(['status'=>false,'msg'=>'数据不存在','waybill'=>$waybill]);
            }
        }else{
            return json(['status'=>false,'msg'=>'靴ID错误']);
        }
    }
	public function lang() {
	    switch (Request::instance()->get('lang')) {
	        case 'cn':
	            cookie('think_lang', 'zh-cn');
	        break;
	        case 'tw':
	            cookie('think_lang', 'zh-tw');
	        break;
	        case 'en':
	            cookie('think_lang', 'en-us');
	        break;
	        //其它语言
	    }
	}
	//获取点数
	public function get_nn_num(): Json
    {
        if (!Request::instance()->isPost()) return json();
        $resultArr = Request::instance()->post('result_json');
        $result = CardPositionNn::JudgeCowCow(json_decode($resultArr,true));
        return json(['status'=>true,'msg'=>$result['word']]);
	}
	public function get_number(): Json
    {
        if (!Request::instance()->isPost()) return json();
        $numberTabId = intval(Request::instance()->post('number_tab_id'));
        $number = NumberTab::getFieldValue($numberTabId,"number");
        if ($number){
            return json(array('data' => $number, 'status' => 1));
        }else{
            return json(array('msg' => '数据出错', 'status' => 0));
        }
	}
	//获取上一局number_tab_id
	public function get_last_number_tab_id(): Json
    {
        if (!Request::instance()->isPost()) return json();
        $tableId = intval(Request::instance()->post('table_id'));
        $bootId = intval(Request::instance()->post('boot_id'));
        $tableInfo = Table::get($tableId);
        if (!$tableInfo) return json(array('msg' => '查询出错','status' => 0));
        if($tableInfo['table_type'] == 0 && $tableInfo['bet_type'] != 2) return json(array('msg' => '该桌不允许删除露珠','status' => 0));
        $lastNumberTabTableId = NumberTab::where(['boot_id' => $bootId, 'bet_status' => 3])->order('id DESC')->limit(1)->value('id');
        if($lastNumberTabTableId > 0){
            return json(['data' => $lastNumberTabTableId,'status' => 1]);
        }else {
            return json(['msg' => '没有可删除的上一铺', 'status' => 0]);
        }
	}

    public function get_result_total(){
        if(Request::instance()->isPost()){
            //获取路单对象
            $table_id = Request::instance()->post('table_id');
            $boot_id = Request::instance()->post('boot_id');
            $game_id = Table::where(array('id' => $table_id))->value('game_id');
            $result = array();
            $result['banker'] = NumberTab::where(array('boot_id' => $boot_id, 'result' => 1, 'table_id' => $table_id))->count();
            $result['player'] = NumberTab::where(array('boot_id' => $boot_id, 'result' => 2, 'table_id' => $table_id))->count();
            $result['tie'] = NumberTab::where(array('boot_id' => $boot_id, 'result' => 3, 'table_id' => $table_id))->count();
            if($game_id == 1){
                //百家乐
                $result['bankerPair'] = NumberTab::where(array('boot_id' => $boot_id, 'pair' => 1, 'table_id' => $table_id))->count();
                $result['playerPair'] = NumberTab::where(array('boot_id' => $boot_id, 'pair' => 2, 'table_id' => $table_id))->count();
                $both = NumberTab::where(array('boot_id' => $boot_id, 'pair' => 3, 'table_id' => $table_id))->count();
                $result['bankerPair'] = $result['bankerPair'] + $both;
                $result['playerPair'] = $result['playerPair'] + $both;
                $result['luckySix'] = NumberTab::where(array('boot_id' => $boot_id, 'result' => 1, 'table_id' => $table_id, 'luck_six'=>1))->count();
            }
            return json(['code'=>1,'data'=>$result]);
        }
        return json(['code'=>0,'data'=>[]]);
    }

}
