<?php
declare (strict_types = 1);

namespace app\handle\controller;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;
use think\Lang;

class Login {
    public function index(){
        if(Session::get('user_info')){
            return redirect('/login/logout');
        }
        return View::fetch();
    }
    /**
     * 处理登录
     */
    public function dologin(){
        if(Request::instance()->post()){
            $username = Request::instance()->post('account');
            $password = Request::instance()->post('password');
            $find = Db::name('user_controller')->where(array('username' => $username, 'is_delete' => 0))->find();
            if(!$find){
                Session::delete('user_info');
				return json(['code' => 0, 'msg' => '用户不存在']);
            }
            if(think_ucenter_md5($password, UC_AUTH_KEY) === $find['password'] && $find['password']){
                Session::set('user_info',$find);
                Db::name('user_controller')->where(array('id' => $find['id']))->update(array('last_login_time' => time(), 'last_login_ip' => get_ip()));
				$tableInfo = Db::name('table')->where(array('id' => $find['table_id']))->find();
                cookie('think_lang',env('lang.default_lang', 'zh-cn'));
				if($tableInfo['game_id'] == 2){
                    $template = $tableInfo['scanner_type'] == 2 ? '/index/tab_dt_sb' : '/index/tab_dt';
                    return json(['code'=>1,'msg'=>'登录成功','url'=>$template]);

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

                    return json(['code'=>1,'msg'=>'登录成功','url'=>$template]);

                }else if($tableInfo['game_id'] == 5){
                    return json(['code'=>1,'msg'=>'登录成功','url'=>'/index/tab_knn']);
                }else if($tableInfo['game_id'] == 1){

                    $template = $tableInfo['scanner_type'] == 2 ? '/index/tab_baccarat_sb' : '/index/tab_baccarat';
                    return json(['code'=>1,'msg'=>'登录成功','url'=>$template]);

                }else if($tableInfo['game_id'] == 6){
                    return json(['code'=>1,'msg'=>'登录成功','url'=>'/index/tab_toning']);
                }else if($tableInfo['game_id'] == 7){
                    return json(['code'=>1,'msg'=>'登录成功','url'=>'/index/tab_dice']);
                }else if($tableInfo['game_id'] == 8){
                    return json(['code'=>1,'msg'=>'登录成功','url'=>'/index/tab_roulette']);
                }else{
					Session::delete('user_info');
					return json(['code'=>0,'msg'=>'账户信息出错']);
				}
            }else{
                Session::delete('user_info');
				return json(['code'=>0,'msg'=>'密码错误']);
            }
        }
    }
    /**
     * 退出登录
     */
    public function logout(){
		Session::delete('user_info');
        return redirect('/login/index');
    }
}