var userid = parseInt($('#userid').val());
var login_token = $('#login_token').val();
var table_id = parseInt($('#table_id').val());
var game_id = parseInt($('#game_id').val());
var account = $('#account').val();
var number_tab_id;
var ludan;
var isCBoot = false;
var isopentime = false;
var num = 0;
var card_info=[];

var websocket = io(websocketProtocol+"://"+websocketUrl+"/?table_id="+table_id+"&account="+account+"&connect=space&userid="+userid+"&login_token="+login_token,{transports: ['websocket']});
websocket.on('reconnecting', (timeout) => {
    //触发重连
    layer.msg('服务断开,正在重新连接...', {
        icon: 16,
        shade: 0.6,
        time:0,
    });
});
websocket.on('reconnect', (timeout) => {
    //重连成功
    layer.closeAll();
    layer.msg('服务重新连接成功');
});
//事件  发送*******************************************************************************************************************
var startBet = function(){
    websocket.emit('startBet',{table_id : table_id, number_tab_id : number_tab_id});
};
var endBet = function (){
    websocket.emit('endBet',{table_id : table_id, number_tab_id : number_tab_id});
};
var resetNumberTab = function(){
    isCBoot = true;
    var betStatus = $("#number_tab_status").val();
    if(betStatus == 1 || betStatus == 2){
        layer.confirm(lang.is_reset_number,{btn: [lang.confirm,lang.cancel],title:lang.message}, function(index){
            websocket.emit('resetNumberTab',{table_id : table_id});
            isCBoot = false;
            layer.close(index);
            $('.roulette-result-num').html('');
            hideRouletteBox();
        },function(index){
            isCBoot = false;
        });
    }else{
        layer.msg(lang.reset_number_fail);
    }
};
var changeBoot = function(){
    isCBoot = true;
    var betStatus = $("#number_tab_status").val();
    if(betStatus == 0 || betStatus == 3){
        layer.confirm(lang.is_to_boot,{btn: [lang.confirm,lang.cancel],title:lang.message}, function(index){
            websocket.emit('changeBoot',{table_id : table_id});
            isCBoot = false;
            layer.close(index);
        },function(index){
            isCBoot = false;
        });
    }else{
        layer.msg(lang.change_boot_false);
    }
};
var resetBoot = function(){
    layer.confirm(lang.is_to_balance,{btn: [lang.confirm,lang.cancel],title:lang.message}, function(index){
        websocket.emit('resetBoot',{table_id : table_id});
        layer.close(index);
    });
};
var opening = function(){
    let result = $('#roulette_result').val();
    websocket.emit('openingRoulette',{table_id : table_id, number_tab_id : number_tab_id, result : result});
};
// 骰宝显示
var showDRouletteBox = function (){
    $('#roulette_result').val('');
    $('.roulette-result-num').html('')
    $('#roulette_result_box').fadeIn();
}
var hideRouletteBox = function (){
    $('#roulette_result_box').addClass('flicker').fadeOut(2400,'linear',function(){
        $('#roulette_result_box').removeClass('flicker');
        $('.roulette-result-num').html('')
    });
}
//事件  发送*******************************************************************************************************************
//事件返回*********************************************************************************************************************
websocket.on('onlineLogin',function(data){
    if (data.table_id === table_id) {
        if(data.status === true){
            setNumberInfo(data.round);
            setBetStatus(data.round.number_tab_status);
            waybillFunc();
            if (data.round.number_tab_status.bet_status != undefined && data.round.number_tab_status.bet_status == 2){
            }
        }else{
            layer.msg(lang[data.msg],{time:0});
        }
    }

});
websocket.on('RepeatedEntry',function(data){
    websocket.close();
    layer.msg(lang[data.msg]);
    setTimeout(function (){
        window.location.href='/login/logout';
    },2000);
});
websocket.on('startBet',function(data){
    if(data.status === true && data.table_id === table_id){
        mp3List = ['start.mp3'];
        audioMp3(mp3List).Play();
        setBetStatus(data.round.number_tab_status);
    }else{
        if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
    }
});
websocket.on('resetNumberTab',function(data){
    if(data.status === true && data.table_id == table_id){
        setNumberInfo(data.round);
        setBetStatus(data.round.number_tab_status);
        $(".countdown").css({"opacity":0,"display":"none"});
        $(".countdown .grab-count").removeClass("count-active");
        $(".begincard .box").animate({"opacity":"0"},function(){
            $(".begincard").fadeOut();

            $(".table-info .nobegin-tip").fadeIn();
            $('.box1').css("background-color","rgba(0, 0, 0, 0.5)");
            $('.box2').css("background-color","rgba(0, 0, 0, 0.5)");
            $('.box3').css("background-color","rgba(0, 0, 0, 0.5)");
            $('.box4').css("background-color","rgba(0, 0, 0, 0.5)");
            $(".begincard .box .list .card").removeClass("begin")
            $(".begincard .card .topleft").html("")
            $(".begincard .card .bottomright").html("")
            $(".list .card .face").css("background-image","")
            $(".begincard .list .draw .rotate").css("display",'none');
        });
        card_info=[];
    }else{
        if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
    }
});
websocket.on('changeBoot',function(data){
    if(data.status === true && data.table_id == table_id){
        setNumberInfo(data.round);
        setBetStatus(data.round.number_tab_status);
        clearBetAmount();
        waybillFunc();
    }else{
        if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
    }
});
websocket.on('resetBoot',function(data){
    if(data.status === true && data.table_id == table_id){
        setNumberInfo(data.round);
        setBetStatus(data.round.number_tab_status);
        waybillFunc();
    }else{
        if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
    }
});
websocket.on('startBetCountDown',function(data){
    if(data.status == true && data.table_id == table_id){
        countDown(data.count_down);
    }
});
websocket.on('endBet',function(data){
    if(data.status === true && data.table_id == table_id){
        $(".countdown").css({"opacity":0,"display":"none"});
        $(".countdown .grab-count").removeClass("count-active");
        mp3List = ['stop_2.mp3'];
        audioMp3(mp3List).Play();
        $(".countdown").css({"opacity":0,"display":"none"});
        $(".countdown .grab-count").removeClass("count-active");
        setBetStatus(data.round.number_tab_status);
    }else{
        if (data.table_id != undefined && data.table_id == table_id) {
            layer.msg(lang[data.msg]);
        }
    }
});
websocket.on('openingRoulette',function(data){
    if(data.status === true && data.table_id == table_id){
        setNumberInfo(data.round);
        setBetStatus(data.round.number_tab_status);
        waybillFunc();
        hideRouletteBox();
    }else{
        if (data.table_id != undefined && data.table_id == table_id) {
            $('.roulette-result-num').html('')
            layer.msg(lang[data.msg]);
        }
    }
});
//事件返回*********************************************************************************************************************

//启动执行
$(function(){
    getLang();
    //视频处理
    $("#video-iframe").attr("src",player+'?url='+flvUrl);
    $(document).keydown(function (e){
        if(e.keyCode == 13){

            var cookieValue = $.cookie("enter_time");
            if(!cookieValue){
                $.cookie("enter_time", 1, { expires: 1/86400*3 });
            }else{
                layer.msg('Please hold on');
                return false
            }

            if(isCBoot == true){
                $('.layui-layer-btn0').click();
                isCBoot = false;
            }else{
                //var keycode = $('#keycode').val();
                var numberTabStatus = $('#number_tab_status').val();
                //if(keycode == '6'){
                if (numberTabStatus == 0) {
                    if(!isopentime){
                        var is_rob = $('#is_rob').val();
                        if(is_rob == 1){
                            startRob();
                        }else{
                            startBet();
                        }
                        $('#keycode').val('');
                    }else{
                        layer.msg("请稍等!");
                    }
                }else if (numberTabStatus == 2) {
                    var result = $('#roulette_result').val();
                    if(result.length == 0){
                        return false;
                    }
                    opening();
                }
            }
        }
        //开局
        if(e.keyCode == 111){
            $('#keycode').val('6');
        }
        //修改当前状态
        if(e.keyCode == 109){
            $('#update_ludan').toggle();
        }
        //换靴
        if(e.keyCode == 107){
            changeBoot();
            $('#keycode').val('');
        }
        //退出登录
        if(e.keyCode == 106){
            if(table_type == 1){
                cutout();
                $('#keycode').val('');
            }else{
                if(bet_type == 2){
                    cutout();
                    $('#keycode').val('');
                }else{
                    loginout();
                    $('#keycode').val('');
                }
            }
        }
        //取消
        if(e.keyCode == 110){
            $('.layui-layer-btn1').click();
        }
        // 停止倒计时
        if(e.keyCode == 96){
            if(game_id == 5 || game_id == 4){
                var number_rob_status=$("#number_rob_status").val();
                var number_tab_status=$("#number_tab_status").val();
                if((number_rob_status==1&&number_tab_status==0)||(number_rob_status==2&&number_tab_status==0)){
                    endRob();
                }else{
                    endBet();
                }
            }else{
                endBet();
            }
        }
        // 骰宝结果选择
        if (game_id == 8){
            if (e.keyCode == 96 || e.keyCode == 97 || e.keyCode == 98 || e.keyCode == 99 || e.keyCode == 100 || e.keyCode == 101 || e.keyCode == 102 || e.keyCode == 103  || e.keyCode == 104  || e.keyCode == 105){
                var num = '';
                switch (e.keyCode){
                    case 96:
                        num = 0;
                        break;
                    case 97:
                        num = 1;
                        break;
                    case 98:
                        num = 2;
                        break;
                    case 99:
                        num = 3;
                        break;
                    case 100:
                        num = 4;
                        break;
                    case 101:
                        num = 5;
                        break;
                    case 102:
                        num = 6;
                        break;
                    case 103:
                        num = 7;
                        break;
                    case 104:
                        num = 8;
                        break;
                    case 105:
                        num = 9;
                        break;
                }
                if (num >= 0){
                    var word = $('.roulette-result-num').html()
                    if(word.length >= 2){
                        return false
                    }
                    $('.roulette-result-num').append(num)
                    var word = $('.roulette-result-num').html()
                    $('#roulette_result').val(word)
                }
            } else if (e.keyCode == 109){
                $('.roulette-result-num').html('')
                $('#roulette_result').val('');
            }
        }
    })
    $(window).resize(function(){
        requestData(ludan);
    })
    audio.addEventListener("ended", nextAudio);
    getTime();
    // 日期
    setInterval(function(){
        getTime();
    }, 1000);
    // 侧栏控台
    $(".control-box").hover(function(){
        $(".control-box").stop().animate({right:"0"})
    },function(){
        $(".control-box").stop().animate({right:"-410px"})
    })
    // 多语言切换
    $('#language').change(function(){
        var language = $('#language').val();
        if(language == "cn" || language == "tw" || language == "en"){
            $.get("/index/lang?lang="+language,function(data){
                location.reload();
            })
        }
    });
    $("#confirm_update_ludan").click(function (){
        retreated();
    });
    $("#cancel_update_ludan").click(function (){
        $('#update_ludan').hide();
    });
    // 色碟方法
    $('.toning-result-num').click(function () {
        $('#toning_result').val(parseInt($(this).html()));
        $(this).addClass("active").siblings().removeClass("active");
    })
})
function loginout(){
    isCBoot = true;
    layer.confirm(lang.is_to_logout,{btn: [lang.confirm,lang.cancel],title:lang.message}, function(index){
        window.location.href='/login/logout';
        isCBoot = false;
        layer.close(index);
    },function(index){
        isCBoot = false;
    });
}
//获取当前语言包
function getLang(){
    $.ajax({
        url:"/index/get_lang",
        type:"POST",
        dataType:"JSON",
        async:false,
        success:function(data){
            if(data.status === 1){
                lang = data.lang;
            }
        }
    })
}
//倒计时
function countDown(time) {
    $(".countdown .num").html(time)
    $(".countdown").css({"opacity":1,"display":"block"});
    $(".countdown .grab-count").addClass("count-active");
    if(time == 10){
        mp3List = ['time_tip_10.mp3'];
        audioMp3(mp3List).Play();
    }
    if(time < 9 && time > 0){
        mp3List = ['time.mp3'];
        audioMp3(mp3List).Play();
    }
    if(time<=0){
        mp3List = ['stop_2.mp3'];
        audioMp3(mp3List).Play();
        $(".countdown").css({"opacity":0,"display":"none"});
        $(".countdown .grab-count").removeClass("count-active");
        return;
    }
}
//播放声音
function audioMp3(mp3List){
    var mp3=new Object();
    mp3.mp3List=mp3List;
    mp3.url="/static/handle/mp3/";
    mp3.auto_play=false;
    mp3.loop=false;
    mp3.Play=function(){
        audio.src=this.url+this.mp3List[0];
        audio.play();
    }
    mp3.Muted=function(){
        audio.muted ? audio.muted = false : audio.muted = true;
    }
    mp3.volumeAdd=function(){
        if(audio.volume.toFixed(1)>=1){
            audio.volume=1
        }else{
            audio.volume = audio.volume + 0.1;
        }
    }
    mp3.volumeMinus=function(){
        if(audio.volume.toFixed(1)<=0){
            audio.volume=0
        }else{
            audio.volume = audio.volume - 0.1;
        }
    }
    return mp3;
}
function Flop(data){
    var whichpoker='',pokerindex='',pokercard='';
    if(data.status==true){
        var which = data.round.position;
        if(game_id == 1){
            switch(which){
                case 11:
                    whichpoker='player-card';
                    pokerindex=1;
                    card_info["player_2"]=data.round.number;
                    break;
                case 12:
                    whichpoker='player-card';
                    pokerindex=0;
                    card_info["player_1"]=data.round.number;
                    break;
                case 13:
                    whichpoker='player-card';
                    pokerindex=2;
                    card_info["player_3"]=data.round.number;
                    break;
                case 21:
                    whichpoker='banker-card';
                    pokerindex=1;
                    card_info["banker_2"]=data.round.number;
                    break;
                case 22:
                    whichpoker='banker-card';
                    pokerindex=0;
                    card_info["banker_1"]=data.round.number;
                    break;
                case 23:
                    whichpoker='banker-card';
                    pokerindex=2;
                    break;
            }
        }else{
            switch(which){
                case 11:
                    whichpoker='player-card';
                    pokerindex=0;
                    card_info["player_1"]=data.round.number;
                    break;
                case 21:
                    whichpoker='banker-card';
                    pokerindex=0;
                    card_info["banker_1"]=data.round.number;
                    break;
            }
        }
        pokercard = data.round.card;
        var $poker = $('.begincard '+'.'+ whichpoker+' .card');
        var pokersrc="/static/handle/faces/"+pokercard+".svg";
        if(pokercard<200){
            var color="#000"
        }else if(pokercard<300){
            var color="#f13b3d"
        }else if(pokercard<400){
            var color="#000"
        }else if(pokercard<500){
            var color="#f13b3d"
        }
        if(data.round.number == 1){
            data.round.number = "A";
        }
        if(data.round.number == 11){
            data.round.number = "J";
        }
        if(data.round.number == 12){
            data.round.number = "Q";
        }
        if(data.round.number == 13){
            data.round.number = "K";
        }
        $poker.eq(pokerindex).find(".topleft").html(data.round.number);
        $poker.eq(pokerindex).find(".bottomright").html(data.round.number);
        $poker.eq(pokerindex).find(".topleft").css("color",color);
        $poker.eq(pokerindex).find(".bottomright").css("color",color);

        if(pokerindex==2){
            $('.begincard '+'.'+ whichpoker +' .draw .rotate').css("display","inline-block");
            $poker.eq(pokerindex).addClass("begin");
            $poker.eq(pokerindex).find(".face").css("background-image","url("+pokersrc+")");
            $(".begincard .banker-card .draw .text").css("text-align","left");
            $(".begincard .player-card .draw .text").css("text-align","right");
        }else{
            $poker.eq(pokerindex).addClass("begin");
            $poker.eq(pokerindex).find(".face").css("background-image","url("+pokersrc+")");
        }
    }
}
// 桌子状态
var setBetStatus = function (BetStatus){
    $('#number_tab_status').val(BetStatus.bet_status);
    if(BetStatus.bet_status==2){
        $('.nobegin-tip').html("");
        $('#show-status-span').html("");
        showDRouletteBox();
    }else if(BetStatus.bet_status==1){
        $('.nobegin-tip').html(lang[BetStatus.bet_msg]);
        $('#show-status-span').html("");
    }else{
        $('.nobegin-tip').html(lang[BetStatus.bet_msg]);
        $('#show-status-span').html("");
    }
};
// 获取桌子数据
var setNumberInfo = function (round){
    number_tab_id = round.number_tab_id
    $('#boot_num').html(round.boot_num);
    $('#number').html(round.number_tab_number);
    $('#boot_id').val(round.boot_id);
};
//修改或者删除录单后从新获取number
var getNumber = function (){
    var query = new Object();
    query.number_tab_id = number_tab_id;
    $.ajax({
        url:"/index/get_number",
        type:"POST",
        dataType:"JSON",
        data:query,
        async:false,
        success:function(data){
            if(data.status == 1){
                $('#number').html(data.data);
            }
        }
    })
};
function nextAudio(){
    num+=1
    if(num<mp3List.length){
        audio.src="/static/handle/mp3/"+mp3List[num];
        audio.play();
    }else{
        audio.pause();
        audio.currentTime = 0.0;
        num=0;
    }
}
function getTime() {
    var today = new Date();
    var h = today.getHours();
    var minute = today.getMinutes()
    var s = today.getSeconds();
    if (h < 10) {
        h = "0" + h;
    }
    if (minute < 10) {
        minute = "0" + minute;
    }
    if (s < 10) {
        s = "0" + s;
    }
    if(lang.lang == 'en-us'){
        var strDate = new Date();
        strDate = strDate.toDateString()
        strDate += " " + h + ":" + minute + ":" + s;
    }else if(lang.lang == 'zh-cn'){
        var strDate = (" " + today.getFullYear() + "年" + (today.getMonth() + 1) + "月" + today.getDate() + "日" + h + ":" + minute + ":" + s);
    }else if(lang.lang == 'zh-tw'){
        var strDate = (" " + today.getFullYear() + "年" + (today.getMonth() + 1) + "月" + today.getDate() + "日" + h + ":" + minute + ":" + s);
    }
    var n_day = today.getDay();
    switch (n_day) {
        case 0:
            var week = lang.sunday;
            break;
        case 1:
            var week = lang.monday;
            break;
        case 2:
            var week = lang.tuesday;
            break;
        case 3:
            var week = lang.wednesday;
            break;
        case 4:
            var week = lang.thursday;
            break;
        case 5:
            var week = lang.friday;
            break;
        case 6:
            var week = lang.saturday;
            break;
        case 7:
            var week = lang.sunday;
            break;
    }
    $('.date .weekend').html(week);
    $('.date .time').html(strDate);
}

// 骰宝
const diceSpriteSrc = `/static/handle/img/sprite.png`;
// 请求所有路单数据，执行画布刷新
function waybillFunc(){
    var data = new Object;
    data.boot_id = $('#boot_id').val();
    data.game_id = game_id;
    var url = "/index/waybill_roulette";
    $.ajax({
        url:url,
        type:"POST",
        dataType:"JSON",
        data:data,
        success:function(data){
            ludan = data;
            requestData(ludan);
        }
    });
}


function requestData(data,ask,askroad){
    var ask=ask||false;
    var askroad=askroad||{
        "askshowroad":false,
        "askbigRoad":false,
        "askbigEyeRoad":false,
        "askpathway":false,
        "askroach":false,
    };
    bigH=$(".canvas-box.big").height();
    bigW=$(".canvas-box.big").width();
    // 计算单位
    unitbig=bigH/6;
    // 计算列个数
    colbig=Math.floor(bigW/unitbig);
    console.log(data)
    CanvasTableRoulette("#canvas3",unitbig,6,colbig,data,ask,askroad);
}

function CanvasTableRoulette(Id,unit,rows,cols,data,ask,askroad){
    var width=unit*cols,
        height=unit*rows;

    $(Id).attr("width",width)
    $(Id).attr("height",height)
    var canvasId=$(Id);
    var ctb=canvasId[0].getContext('2d');
    ctb.lineWidth = 1;//线条宽度
    ctb.strokeStyle = "#919191";//线条颜色
    ctb.beginPath();
    ctb.moveTo(0, 0.5);
    ctb.lineTo(width, 0.5);
    for (var i = 0; i <= rows; i++) {
        ctb.moveTo(0, unit*i);
        ctb.lineTo(width, unit*i);
    }
    ctb.closePath()
    ctb.stroke();
    ctb.beginPath();
    ctb.moveTo(0.5, 0);
    ctb.lineTo(0.5, height);
    for (var j = 1; j <= cols; j++) {
        ctb.moveTo(unit*j,0);
        ctb.lineTo(unit*j,height);
    }
    ctb.closePath()
    ctb.stroke();
    if(data.status){
        switch(true){
            // 判断是否滚动
            case Id=="#canvas3":
                var showRoad=data.waybill;

                if(showRoad!=''){
                    var roadType="showWay"
                    cutRoad(roadType,ctb,unit,showRoad,cols,ask,askroad.askshowroad);
                }
                break;
        }
    }
}
// 前端路单数据截取
function cutRoad(roadType,ctb,unit,roadData,cols,ask,askroad){
    var L=roadData.length;
    var new_roadData=[];
    var Tab=0
    if(roadType=="showWay"||roadType=="bigWay"){
        if(ask&&askroad){
            Tab=cols;
        }else{
            Tab=cols-1;
        }
    }else{
        if(ask&&askroad){
            Tab=cols-1;
        }else{
            Tab=cols-2;
        }
    }
    var start_x=cols/2+0.25;
    if(L>=1){
        var last_x=roadData[L-1].show_x
        if(last_x>Tab){
            var cut=last_x-Tab
            $.each(roadData,function(i,v){
                if(v.show_x>cut){
                    new_roadData.push(v)
                }
            })
        }else{
            new_roadData=roadData;
            cut=0;
        }
    }else{
        new_roadData=roadData;
        cut=0;
    }
    $.each(new_roadData,function(i,v){
        if(roadType=="showWay"){
            SoloPath(ctb,unit,v.show_x-cut,v.show_y,v.result)
        }
    })
}
function SoloPath(ctb,unit,x,y,type){
    ctb.beginPath();
    ctb.lineWidth = 0.5;
    ctb.strokeStyle = "#000";
    var radius=unit/2||0;
    var black = ['2','4','6','8','10','11','13','15','17','20','22','24','26','28','29','31','33','35'];
    var red = ['1','3','5','7','9','12','14','16','18','19','21','23','25','27','30','32','34','36'];
    var fonts=type;
    if($.inArray(type,black) != -1){
        var color='#636363';
        ctb.strokeStyle = "#636363";
    }
    if($.inArray(type,red) != -1){
        var color='#f54f42';
        ctb.strokeStyle = "#f54f42";
    }
    if(type == 0){
        var color='#5db646';
        ctb.strokeStyle = "#5db646";
    }
    ctb.arc(radius+unit*(x-1), radius+unit*(y-1), unit*0.45, 0, Math.PI * 2);
    ctb.fillStyle=color;
    ctb.fill();
    ctb.font=unit*0.67+"px Arial";
    ctb.fillStyle ="#fff" ; // 颜色
    ctb.textAlign = 'center';
    ctb.textBaseline = 'middle';
    ctb.fillText(fonts,radius+unit*(x-1),radius+unit*(y-1));
    ctb.stroke();

}