var eodds = new Array();
var lodds = new Array();
//L为亚指,O为欧指,T为大小
var selectOddsType = _config.defaultOddsType;

var selectCompanyId = 100;
var selectCompanyIndex = 0;
var oddsData = new Object();
var oddsDetailId = "3";
//初始化公司下拉列表
function InitSelectOddsList() {
    const listCompany = window.helper().listCompany();

    // eodds = listCompany.map(item => ({
    //     id: item.value,
    //     name: item.label
    // }));

    // lodds = listCompany.map(item => ({
    //     id: item.value,
    //     name: item.label
    // }));
    eodds = [
        // { id: 9999, name: "K - Sport" },
        { id: 281, name: "Bet365" },
        { id: 80, name: "Macauslot" },
        { id: 422, name: "Sportingbet" },
        { id: 1129, name: "Lottery Official" },
        { id: 82, name: "Ladbrokes" },
        { id: 474, name: "Sbobet" },
        { id: 517, name: "Mansion88" },
        { id: 115, name: "William Hill" },
        { id: 81, name: "Vcbet" },
        { id: 432, name: "HK Jockey Club" },
        { id: 90, name: "Easybets" },
        { id: 659, name: "Wewbet" },
        { id: 16, name: "10BET" },
        { id: 18, name: "12BET" },
        { id: 976, name: "18BET" },
        { id: 173, name: "bet-at-home" },
        { id: 255, name: "Bwin" },
        { id: 88, name: "Coral" },
        { id: 545, name: "Crown" },
        { id: 71, name: "Eurobet" },
        { id: 70, name: "Expekt" },
        { id: 158, name: "Gamebookers" },
        { id: 649, name: "IBCBET" },
        { id: 104, name: "Interwetten" },
        { id: 97, name: "Nike" },
        { id: 4, name: "Nordicbet" },
        { id: 370, name: "Oddset" },
        { id: 177, name: "Pinnacle" },
        { id: 110, name: "SNAI" },
        { id: 60, name: "STS" },
        { id: 450, name: "TOTO" },
    ]

    lodds = [
        // { id: 100, name: "K - Sport" },
        { id: 31, name: "Sbobet" },
        { id: 8, name: "Bet365" },
        { id: 23, name: "188bet" },
        { id: 24, name: "12bet" },
        { id: 42, name: "18Bet" },
        { id: 1, name: "Macauslot" },
        { id: 4, name: "Ladbrokes" },
        { id: 12, name: "Easybet" },
    ]
}

//设定赔率选择的默认值，按需重写此方法
function InitDefaultOddsSetting() {
    var oddsType = getCookie("selectOddsType");
    var companyId = getCookie("selectCompanyId");
    var companyIndex = getCookie("selectCompanyIndex");
    if (oddsType != null) {
        selectOddsType = oddsType;
    }

    if (companyId != null) {
        selectCompanyId = companyId;
        selectCompanyIndex = companyIndex;
    } else if (selectOddsType == "T" || selectOddsType == "L") {
        selectCompanyId = 31;
        selectCompanyIndex = GetSelectCompanyIndex(selectOddsType, selectCompanyId);
    } else if (selectOddsType == "O") {
        selectCompanyId = 31;
        selectCompanyIndex = GetSelectCompanyIndex(selectOddsType, selectCompanyId);
    }
}

//获取公司在下拉列表的索引
function GetSelectCompanyIndex(oddsType, companyId) {
    companyId = parseInt(companyId);
    var companyList = oddsType == "O" ? eodds : lodds;
    for (var i = 0; i < companyList.length; i++) {
        if (companyList[i].id == companyId)
            return i;
    }
}

function InitOdds(sclassId, subSclassId, matchSeason, selectRound, callback) {
    InitSelectOddsList();
    InitDefaultOddsSetting();
    if (selectOddsType == "O") InitCompanyList(eodds);
    else InitCompanyList(lodds);
    var url = dbUrl+"/ajax/LeagueOddsAjax?sclassId=" + sclassId + "&subSclassId=" + subSclassId + "&matchSeason=" + matchSeason + "&round=" + selectRound;
    bomHelper.ajaxGet(url, function (data) {
        eval(data);
        callback && callback(data);
    });
}

function GetOddsData(sclassId, subSclassId, matchSeason, selectRound, callback) {
    oddsData = new Object();
    var url = dbUrl+"/ajax/LeagueOddsAjax?sclassId=" + sclassId + "&subSclassId=" + subSclassId + "&matchSeason=" + matchSeason + "&round=" + selectRound;
    bomHelper.ajaxGet(url, function (data) {
        eval(data);
        callback && callback(data);
    })
}

function oddsChange(value) {
    document.getElementById("rdoL").checked = false;
    document.getElementById("rdoO").checked = false;
    document.getElementById("rdoT").checked = false;
    document.getElementById("rdo" + value).checked = true;
    $('.mobile__checkbox input').prop('checked', false)
    $(`.mobile__checkbox #rdo${value}`).prop('checked', true)

    selectOddsType = value;
    writeCookie("selectOddsType", value);
    if (selectOddsType == "O")
        SelectOddsChange(eodds);
    else
        SelectOddsChange(lodds);
}

function InitOddsChange(value) {
    document.getElementById("rdoL").checked = false;
    document.getElementById("rdoO").checked = false;
    document.getElementById("rdoT").checked = false;
    document.getElementById("rdo" + value).checked = true;
    selectOddsType = value;
    writeCookie("selectOddsType", value);
    if (selectOddsType == "O")
        SelectOddsChange(eodds, true);
    else
        SelectOddsChange(lodds, true);
}

//初始化公司下拉列表,默认选择亚指，Crown
function InitCompanyList(oddsList) {
    var oddsCompany = document.getElementById("oddsCompany");
    if (!oddsCompany) return;


    for (var i = 0; i < oddsList.length; i++) {
        const oddsListName = oddsList[i].name;
        const oddsListId = oddsList[i].id;
        oddsCompany.options.add(new Option(oddsListName, oddsListId));
        $( "#company-list .dropdown-menu .dropdown-menu-inner" ).append(`<div for="opt2" class="option cursor-pointer" data-id="${oddsListId}">${oddsListName}</div>`);
    }

    oddsCompany.options.selectedIndex = selectCompanyIndex;
    const oddsCompanySelected = $('#oddsCompany').find('option:selected');

    $('#company-list .dropdown-toggle').text(oddsCompanySelected.text());
    $('#company-list .dropdown-menu .option').removeClass('active')
    $('#company-list .dropdown-menu .option[data-id="' + oddsCompanySelected.val() + '"]').addClass('active');

    if (SclassID == "41" || SclassID == "1366") {
        $("#oddsCompany").prop("disabled", true);
    }

    var existingElement = document.getElementById("oddsCompanyCustom");
    if (existingElement) {
        var oddsCompanyCustom = oddsCompany.cloneNode(true);
        oddsCompanyCustom.id = "oddsCompanyCustom";
        document.getElementById("oddsCompanyCustom").replaceWith(oddsCompanyCustom);
    }
}

//赔率选择事件
function SelectOddsChange(oddsList, isInit = false) {
    var oddsCompany = document.getElementById("oddsCompany");

    var index = oddsCompany.selectedIndex;//获取当前选择项的索引.
    var selectText = oddsCompany.options[index].text;
    oddsCompany.length = 0;
    //亚指大小Crown的INDEX为1，欧指Crown的INDEX为19
    var selectNewIndex = 1;
    var selectValue = 3;
    if (selectOddsType == "O") {
        selectNewIndex = 19;
        selectValue = 545;
    }
    //由欧指切换成亚指，大小时，如果当前选择的公司不在亚指，大小公司范围内，默认显示Crown
    $( "#company-list .dropdown-menu .dropdown-menu-inner" ).html('');
    for (var i = 0; i < oddsList.length; i++) {
        const oddsListName = oddsList[i].name;
        const oddsListId = oddsList[i].id;
        oddsCompany.options.add(new Option(oddsListName, oddsListId));
        $( "#company-list .dropdown-menu .dropdown-menu-inner" ).append(`<div for="opt2" class="option cursor-pointer" data-id="${oddsListId}">${oddsListName}</div>`);
        if (selectText == oddsList[i].name) {
            selectNewIndex = i;
            selectValue = oddsList[i].id;
        }
    }
    oddsCompany.options.selectedIndex = selectNewIndex;
    selectCompanyId = selectValue;
    $('#oddsCompany').trigger('change');
    GetOddsDetailId();
    ShowScheduleOdds(selectValue);
}

function changeOddsType(value) {
    if (selectOddsType == "O")
        SelectOddsChange(eodds);
    else
        SelectOddsChange(lodds);
}

function ShowScheduleOdds(companyId) {
    var doc = $("tr[id], div.match[id]");
    var scheduleList = new Array();
    if (window.location.href.toLowerCase().indexOf("leateam") > 0)
        scheduleList = arrScheduleList;
    else {
        if (window.location.href.toLowerCase().indexOf("subleague") > 0) {
            if (currSubLeague.length <= 7 || (currSubLeague.length > 7 && currSubLeague[7] == 0))
                scheduleList = jh["R_" + selectRound];
            else {
                for (var i = 0; i < jh["R_" + selectRound].length; i++) {
                    var oneScheKind = jh["R_" + selectRound][i];
                    for (var j = 4; j < oneScheKind.length; j++)
                        scheduleList.push(oneScheKind[j]);
                }
            }
        } else {
            if (window.location.href.toLowerCase().includes('tran-dau-cup')) {
                var selectGroupId = currGroupId == "" ? "" : fenZuShu[currGroupId];
                if (currCupMatch.length <= 7 || (currCupMatch.length > 7 && currCupMatch[7] == 0))
                    scheduleList = jh["G" + currCupMatch[0] + selectGroupId];
                else {
                    for (var i = 0; i < jh["G" + currCupMatch[0] + selectGroupId].length; i++) {
                        var oneScheKind = jh["G" + currCupMatch[0] + selectGroupId][i];
                        for (var j = 4; j < oneScheKind.length; j++)
                            scheduleList.push(oneScheKind[j]);
                    }
                }
            }
            else
                scheduleList = jh["R_" + selectRound];
        }
    }
    for (var i = 0; i < doc.length; i++) {
        var scheId = doc[i].id;
        var up = "";
        var odds = "";
        var down = "";
        var obj = null;
        if (typeof(scheduleList) != "undefined") {
            for (var k = 0; k < scheduleList.length; k++) {
                if (scheId == scheduleList[k][0]) {
                    obj = scheduleList[k];
                    break;
                }
            }
        }
        var oddsList = oddsData[selectOddsType + "_" + scheId];
        if (oddsList != undefined) {
            for (var j = 0; j < oddsList.length; j++) {
                var data = oddsList[j];
                if (data[0] == companyId) {
                    if (data[1] != "" && data[1] != undefined) {
                        up = Number(data[1]).toFixed(2);
                        up = selectOddsType == "O" ? oTool.changePL(_oddsType, up, true) : oTool.changePL(_oddsType, up);
                    }
                    if (selectOddsType == "L") {
                        odds = Goal2GoalCn(data[2]);
                    } else {
                        if (selectOddsType == "T")
                            odds = Goal2CnOU(data[2]);
                        else {
                            if (data[2] != "" && data[2] != undefined) {
                                odds = Number(data[2]).toFixed(2);
                                odds = oTool.changePL(_oddsType, odds, true);
                            }
                        }
                    }
                    if (data[3] != "" && data[3] != undefined) {
                        down = Number(data[3]).toFixed(2);
                        down = selectOddsType == "O" ? oTool.changePL(_oddsType, down, true) : oTool.changePL(_oddsType, down);
                    }
                    if (obj != null && obj[2] == -1) {
                        var scoreArr = obj[6].split("-");
                        var homeScore = parseInt(scoreArr[0]);
                        var guestScore = parseInt(scoreArr[1]);
                        if (selectOddsType == "L") {
                            if (homeScore - data[2] > guestScore && up != "") up = "<span class='tocolor'>" + up + "</span>";
                            else if (homeScore - data[2] < guestScore && down != "") down = "<span class='tocolor'>" + down + "</span>";
                        }
                        if (selectOddsType == "T") {
                            if (homeScore + guestScore > data[2] && up != "") up = "<span class='tocolor'>" + up + "</span>";
                            else if (homeScore + guestScore < data[2] && down != "") down = "<span class='tocolor'>" + down + "</span>";
                        }
                        if (selectOddsType == "O") {
                            if (homeScore > guestScore && up != "") up = "<span class='tocolor'>" + up + "</span>";
                            else if (homeScore < guestScore && down != "") down = "<span class='tocolor'>" + down + "</span>";
                            else if (odds != "") odds = "<span class='tocolor'>" + odds + "</span>";
                        }
                    }
                    break;
                }
            }
        }
        var temp = up != "" || odds != "" || down != "" ? GoOddsDetailUrl(scheId) + up : up;
        if (doc[i].tagName.toLowerCase() === "tr") {
            doc[i].childNodes[5].innerHTML = `<div class="box-des-content" data-before-content='Chủ'><div class="box-set">${!temp || temp == '' ? '-' : temp}</div></div>`;
            doc[i].childNodes[6].innerHTML = `<div class="box-des-content" data-before-content='Hòa'><div class="box-set">${!odds || odds == '' ? '-' : odds}</div></div>`;
            doc[i].childNodes[7].innerHTML = `<div class="box-des-content" data-before-content='Khách'><div class="box-set">${!down || down == '' ? '-' : down}</div></div>`;
        } else if (doc[i].tagName.toLowerCase() === "div") {
            var oddsDivs = $(doc[i]).find('.bottom-table .odds > div');
            $(oddsDivs[0]).html(`<div class="box-des-content" data-before-content='Chủ'><div class="box-set">${!temp || temp == '' ? '-' : temp}</div></div>`);
            $(oddsDivs[1]).html(`<div class="box-des-content" data-before-content='Hòa'><div class="box-set">${!odds || odds == '' ? '-' : odds}</div></div>`);
            $(oddsDivs[2]).html(`<div class="box-des-content" data-before-content='Khách'><div class="box-set">${!down || down == '' ? '-' : down}</div></div>`);
        }
    }
}




//返回首次打开页面时的赔率数据
function GetDefaultScheduleOdds(obj) {
    var up = "";
    var odds = "";
    var down = "";

    var oddsList = oddsData[selectOddsType + "_" + obj[0]];
    if (oddsList != undefined) {
        for (var j = 0; j < oddsList.length; j++) {
            var data = oddsList[j];
            if (data[0] == selectCompanyId) {
                if (data[1]) {
                    up = Number(data[1]).toFixed(2);
                    up = selectOddsType == "O" ? oTool.changePL(_oddsType, up, true) : oTool.changePL(_oddsType, up);
                }
                if (selectOddsType == "L") {
                    odds = Goal2GoalCn(data[2]);
                } else {
                    if (selectOddsType == "T")
                        odds = Goal2CnOU(data[2]);
                    else {
                        if (data[2]) {
                            odds = Number(data[2]).toFixed(2);
                            odds = oTool.changePL(_oddsType, odds, true);
                        }
                    }
                }
                if (data[3]) {
                    down = Number(data[3]).toFixed(2);
                    down = selectOddsType == "O" ? oTool.changePL(_oddsType, down, true) : oTool.changePL(_oddsType, down);
                }
                if (obj[2] == -1) {
                    var scoreArr = obj[6].split("-");
                    var homeScore = parseInt(scoreArr[0]);
                    var guestScore = parseInt(scoreArr[1]);
                    if (selectOddsType == "L") {
                        if (homeScore - data[2] > guestScore) up = "<span class='tocolor'>" + up + "</span>";
                        else if (homeScore - data[2] < guestScore) down = "<span class='tocolor'>" + down + "</span>";
                    }
                    if (selectOddsType == "T") {
                        if (homeScore + guestScore > data[2]) up = "<span class='tocolor'>" + up + "</span>";
                        else if (homeScore + guestScore < data[2]) down = "<span class='tocolor'>" + down + "</span>";
                    }
                    if (selectOddsType == "O") {
                        if (homeScore > guestScore) up = "<span class='tocolor'>" + up + "</span>";
                        else if (homeScore < guestScore) down = "<span class='tocolor'>" + down + "</span>";
                        else odds = "<span class='tocolor'>" + odds + "</span>";
                    }
                }
                break;
            }
        }
    }
    return [up, odds, down];
}

//公司选择事件
function OddsCompanyChange(obj) {
    selectCompanyId = obj.value;
    writeCookie("selectCompanyId", obj.value);
    writeCookie("selectCompanyIndex", obj.selectedIndex)
    GetOddsDetailId();
    ShowScheduleOdds(obj.value);
}


//获取赔率明细链接
function GoOddsDetailUrl(scheId) {

    var temp = selectOddsType == "L" ? "handicap" : (selectOddsType == "T" ? "overunder" : "1x2");
    return oddsDetailId != "" ? '<div class="hideBox"><a class="hideLink" href="http://vip.win007.com/changeDetail/' + temp + '.aspx?id=' + scheId + '&companyid=' + oddsDetailId + '&l=0" target="_blank"></a></div>' : '';
}
//获取赔率公司Id，赔率类型或者赔率公司切换时使用
function GetOddsDetailId() {
    var oddsCompany = document.getElementById("oddsCompany");
    var index = oddsCompany.selectedIndex;//获取当前选择项的索引.
    var selectText = oddsCompany.options[index].text;
    oddsDetailId = "";
    if (selectOddsType == "O") {
        for (var i = 0; i < lodds.length; i++) {
            if (selectText == lodds[i].name) {
                oddsDetailId = lodds[i].id;
                break;
            }
        }
    }
    else {
        for (var i = 0; i < lodds.length; i++) {
            if (selectText == lodds[i].name) {
                oddsDetailId = lodds[i].id;
                break;
            }
        }
    }
}

$(document).ready(function() {
    $('#oddsCompany').on('change', function() {
        selectCompanyId = this.value;
        $('#company-list .dropdown-toggle').text($(this).find('option:selected').text());
        $('#company-list .dropdown-menu .option').removeClass('active')
        $('#company-list .dropdown-menu .option[data-id="' + selectCompanyId + '"]').addClass('active');
        writeCookie("selectCompanyId", this.value);
        writeCookie("selectCompanyIndex", this.selectedIndex);
        GetOddsDetailId();
        ShowScheduleOdds(this.value);
    });

    $(document).on('click', '#company-list .option',function() {
        $('#oddsCompany').val($(this).data('id'));
        $('#oddsCompany').trigger('change');
        $('#company-list .dropdown-toggle').text($(this).text());
        $('#company-list .dropdown-menu .option').removeClass('active')
        $(this).addClass('active');
    });
});
