async function initJackpotWrap(){
    if (typeof jackpotTasksMapping == 'undefined'){
        showLoading()
        await $.get('/activity/getActBasicConfig/jackpot',function(response){
            hideLoading()
            if (typeof response == 'string')response = JSON.parse(response)
            jackpotTasksMapping = response.data
        })
    }
    $("#reward_info").empty()
    commonLineTitles =[
        {"tname":"bouns消耗/倍率","vname":"pro"},
        {"tname":"修正值","vname":"fix"}
    ];

    // 金币老虎机基础配置
    $("#reward_info").append(getJackpotBasicSettingHtml());

    // prd算法概率配置
    $("#reward_info").append(getJackpotPrdSettingHtml());

    $("#reward_info").append(getJackpotHtmlWrap());
}
function initRewardJackpot(){
    initJackpotWrap().then(function (){
        console.log('activity_extra_data',activity_extra_data)
        activity_extra_data.yStages && $.each(activity_extra_data.yStages,function(i, o){
            // $("#jackpot_table_wrap").append(getJackpotHtml());
            $('.btnAddJackpotLvStage').click()
            $('#jackpot_lv_table_'+i).find('input[name="jackpot['+i+'][start]"]').val(o.start)
            $('#jackpot_lv_table_'+i).find('input[name="jackpot['+i+'][end]"]').val(o.end)

            $('#jackpotLvStageBtnGroup_'+i).empty().append('<button class="btn btn-primary asyncLoadConfigBtn" style="" type="button" onclick="asyncLoadJackpotConfig('+i+')">加载配置</button>')
            $('#submitBtn').hide();
        })

        console.log('extra_reward',extra_reward)
        extra_reward.prdConf && $.each(extra_reward.prdConf, function(i1, o1){
            addPrdLine();
            $(`input[name="prdConf[${i1}][0]`).val(o1[0])
            $(`input[name="prdConf[${i1}][1]`).val(o1[1])
            console.log(o1);
        })
    })

}

function changeTypeToJackpot() {
    initJackpotWrap().then()
}
function getJackpotHtmlWrap() {
    jackpotLvStagesCnt = 0;
    jackpotYStageArr = [];
    jackpotStagesArr = [];
    jackpotShushuArr = [];
    var html ='';
    html +='<div class="form-group" id="jackpot_table_wrap" style="margin:0px;position:relative;padding-bottom: 20px">'+
        '<button class="btn btn-primary btnAddJackpotLvStage"  type="button" onclick="addJackpotLvStage(this)">添加等级区间</button>'+
        '<button class="btn btn-danger"   type="button" onclick="delJackpotLvStage()">删除等级区间</button>'+
        '</div>';

    return html;
}

// 金币老虎机bouns修正
function jackpotBonusFixed() {
    $("#reward_info").append(commonTable('金币老虎机bouns修正'))
    if(Object.prototype.toString.call(extra_reward.fixCo) === '[object Object]'&&Object.keys(extra_reward.fixCo).length>0) {
        $.each(extra_reward.fixCo,function(key,val) {
            console.log(val);
            commonLineNum++;
            $("#commonLine").append(commonLine(val));
        });
    }
}

// 添加第一层级 等级区间
function addJackpotLvStage(obj){
    var html = getJackpotHtml();
    $(obj).before(html)
}
function getJackpotHtml() {
    jackpotLvStagesCnt++;
    jackpotYStageArr[jackpotLvStagesCnt] = 0;
    var html ='';
    html +='<div class="form-group jackpot_lv_table" data-idx="'+jackpotLvStagesCnt+'" id="jackpot_lv_table_'+jackpotLvStagesCnt+'" style="margin:0px;padding-bottom: 15px;border:solid 1px;">';
    html +='<div class="row" style="padding: 0 30px"><lable>等级区间：<input name="jackpot['+jackpotLvStagesCnt+'][start]">~<input name="jackpot['+jackpotLvStagesCnt+'][end]"></lable></div>';
    html += '<div class="row " id="jackpotLvStageBtnGroup_'+jackpotLvStagesCnt+'" style="padding: 0 30px">' +
        '<button class="btn btn-primary btnAddJackpotYStage" style="" type="button" onclick="addJackpotYStage(this)">添加Y值区间</button>'+
        '<button class="btn btn-danger btnDelJackpotYStage"  style="" type="button" onclick="delJackpotYStage(this)">删除Y值区间</button>' +
        '</div>'
    html +='</div>';

    return html;
}
function delJackpotLvStage (){
    if(jackpotLvStagesCnt > 0){
        jackpotStagesArr[jackpotLvStagesCnt] = 0;
        jackpotLvStagesCnt--;
        $('#jackpot_table_wrap').find('.jackpot_lv_table:last').remove()
    }
}

// 添加第二层级 Y值区间
function addJackpotYStage(obj) {
    let lvIdx = $(obj).parents('.jackpot_lv_table').data('idx')
    let yIdx = ++jackpotYStageArr[lvIdx];
    let yLvIdx = `${lvIdx}_${yIdx}`;
    jackpotShushuArr[yLvIdx] = 0;
    console.log(lvIdx);
    console.log(yIdx);
    var html ='';
    html +='<div class="form-group jackpot_y_table" data-idx="'+yIdx+'" id="jackpot_y_table_'+yLvIdx+'" style="margin:0px;padding-bottom: 15px;border:solid 1px;">';
    html +='<div class="row" style="padding: 0 30px"><lable>Y值区间：<input name="jackpot['+lvIdx+'][stages]['+yIdx+'][start]">~<input name="jackpot['+lvIdx+'][stages]['+yIdx+'][end]"></lable></div>';
    html += '<div class="row " id="jackpotShushuStageBtnGroup_'+yLvIdx+'" style="padding: 0 30px">' +
        '<button class="btn btn-primary btnAddJackpotShushuStage" style="" type="button" onclick="addJackpotShushuStage(this)">添加数数区间</button>'+
        '<button class="btn btn-danger btnDelJackpotShushuStage"  style="" type="button" onclick="delJackpotShushuStage(this)">删除数数区间</button>' +
        '</div>'
    html +='</div>';

    $(obj).before(html)
}
function delJackpotYStage (obj){
    let lvIdx = $(obj).parents('.jackpot_lv_table').data('idx');
    if(jackpotYStageArr[lvIdx] > 0){
        let yIdx = jackpotYStageArr[lvIdx]--;
        let yLvIdx = `${lvIdx}_${yIdx}`;
        jackpotShushuArr[yLvIdx] = 0;
        $(obj).parents('.jackpot_lv_table').find('.jackpot_y_table:last').remove()
    }
}


// 添加数数分组层级
function addJackpotShushuStage(obj) {
    let lvIdx = $(obj).parents('.jackpot_lv_table').data('idx')
    let yIdx = $(obj).parents('.jackpot_y_table').data('idx')
    let yLvIdx = `${lvIdx}_${yIdx}`;
    let ShushuIdx = ++jackpotShushuArr[yLvIdx]
    let rewardIdx = `${lvIdx}_${yIdx}_${ShushuIdx}`;
    jackpotStagesArr[rewardIdx] = -1;
    var html = generateJackpotShushuHtml(lvIdx, yIdx, ShushuIdx);

    $(obj).parent('.row').before(html)
    $('.select2').select2({})
}
function delJackpotShushuStage(obj) {
    let lvIdx = $(obj).parents('.jackpot_lv_table').data('idx');
    let yIdx = $(obj).parents('.jackpot_y_table').data('idx');
    let yLvIdx = `${lvIdx}_${yIdx}`;
    if(jackpotShushuArr[yLvIdx] < 1)return;
    let shushuIdx = jackpotShushuArr[yLvIdx]--
    let rewardIdx = `${lvIdx}_${yIdx}_${shushuIdx}`;
    jackpotStagesArr[rewardIdx] = -1;
    $(obj).parents('.jackpot_y_table').find('.jackpot_shushu_table:last').remove();
}

generateJackpotShushuHtml = (idx1, idx2, idx3) => {
    let optionsHtml = getShushuSelectorOptions()
    return html = `
        <div class="form-group jackpot_shushu_table" data-idx="${idx3}" id="jackpot_shushu_table_${idx1}_${idx2}_${idx3}" style="margin:15px;padding-bottom: 15px">
           <div class="ibox-title" style="border-top: 0;">
                <lable>数数分组：</lable>
                <select class="form-control select2 jackpotShushuSelector" name="jackpot[${idx1}][stages][${idx2}][stages][${idx3}][shushu][]" multiple>
                ${optionsHtml}
                </select>
        </div>
        <table class="table table-bordered" style="margin: 15px">
        <thead>
        <tr>
        <th>ID</th>
        <th>任务类型</th>
        <th>任务值</th>
        <th>修正频率</th>
        <th>Jackpot基础值</th>
        <th>Jackpot中级值</th>
        <th>Jackpot高级值</th>
        <th>奖励</th
        ><th>下注值</th>
        <th>操作</th>
        </tr>
        </thead>
        <tbody class="table_body_jackpot">
        </tbody><tr><td colspan="10"><div class="text-center">
        <botton class="btn btn-primary addJackpotNum" id="addRank" onclick="addJackpotNum(this)">添加</botton>
        <botton class="btn btn-danger del-tr" onclick="delJackpotNum(this)">删除</botton>
        </div></td></tr></table></div>` ;
}

function addJackpotNum(obj){
    let lvIdx = $(obj).parents('.jackpot_lv_table').data('idx')
    let yIdx = $(obj).parents('.jackpot_y_table').data('idx')
    let ShushuIdx = $(obj).parents('.jackpot_shushu_table').data('idx')
    let rewardIdx = `${lvIdx}_${yIdx}_${ShushuIdx}`;
    let stageIdx = ++jackpotStagesArr[rewardIdx];
    var data ={"id":jackpotStagesArr[rewardIdx],"stage":stageIdx,"taskType":1,"target":0,"frequency":50};
    var html = jackpotTableTR(lvIdx, yIdx, ShushuIdx, data);
    $(obj).parents('.jackpot_shushu_table').find('.table_body_jackpot').append(html);
}

//删排行奖励行
function delJackpotNum(obj){
    let lvIdx = $(obj).parents('.jackpot_lv_table').data('idx')
    let yIdx = $(obj).parents('.jackpot_y_table').data('idx')
    let ShushuIdx = $(obj).parents('.jackpot_shushu_table').data('idx')
    let rewardIdx = `${lvIdx}_${yIdx}_${ShushuIdx}`;
    jackpotStagesArr[rewardIdx];
    if(jackpotStagesArr[rewardIdx]>0){
        $(obj).parents('.jackpot_shushu_table').find('.table_body_jackpot').find('tr:last').remove();
        jackpotStagesArr[rewardIdx]--;
    }
}

//奖励阶段行数据html
function jackpotTableTR(idx1, idx2, idx3, data){
    var stageIdx = data['stage'];
    var stage = data['id'];
    var reward = data['prize']!=undefined?JSON.stringify(data['prize']):'[]';
    var reward_show_arr = JSON.parse(reward);
    reward = escape(reward);

    var bet = data['bet']!=undefined?JSON.stringify(data['bet']):'[]';
    var bet_show_arr = JSON.parse(bet);
    bet = escape(bet);

    var html ='';
    html+='<tr id="jackpotInfo_'+stageIdx+'" class="commonStageRewardTr">';
    html +=`<td style="width: 5%;"><input type="text" class="form-control " name="jackpot[${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][id]" value="${stageIdx+1}" readonly></td>`;

    html +=`<td style="width: 10%;"><select class="form-control" name="jackpot[${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][taskType]">`;
    $.each(jackpotTasksMapping, function (i,o){
        let selectedStr = "";
        if(i == data['taskType']){
            selectedStr = "selected";
        }
        html += `<option ${selectedStr} value="${i}">${o}</option>`;
    })
    html +='</select></td>';
    html +=`<td style="width: 10%;"><input type="text" class="form-control" name="jackpot[${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][target]"    value="${data['target']}"></td>`;
    html +=`<td style="width: 10%;"><input type="text" class="form-control" name="jackpot[${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][frequency]" value="${data['frequency']}"></td>`;
    html +=`<td style="width: 10%;"><input type="text" class="form-control" name="jackpot[${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][base]" value="0"></td>`;
    html +=`<td style="width: 10%;"><input type="text" class="form-control" name="jackpot[${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][mid]" value="0"></td>`;
    html +=`<td style="width: 10%;"><input type="text" class="form-control" name="jackpot[${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][high]" value="0"></td>`;
    html +='<td class="prizeShow showJackpotPrize_'+stageIdx+'">';
    if(reward_show_arr.length>0){
        for(var j=0;j<reward_show_arr.length;j++){
            html+= chestPropsHtml(reward_show_arr[j]);
        }
    }
    html +='</td>';
    html +=`<td class="betShow  showJackpotBet_${idx1}_${idx2}_${idx3}_${stageIdx}">`;
    if(bet_show_arr.length>0){
        for(var j=0;j<bet_show_arr.length;j++){
            var tempBet = bet_show_arr[j];
            html += `<span class="btn btn-outline btn-primary" id="${idx1}_${idx2}_${idx3}_${stageIdx}_${tempBet}" onclick="jackpotBetDelFunction(${idx1},${idx2},${idx3},${stageIdx},${tempBet}>${tempBet}</span>`;
        }
    }
    html +='</td>';
    html +=`<input type="hidden" name="jackpot[${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][prize]" value="${reward}" class="prizeInput">`;
    html +=`<input type="hidden" name="jackpot[${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][bet]" value="${bet}">`;
    html +='<td style="width: 15%;">' +
        '<button type="button" class="btn btn-outline btn-success" onclick="setPrize(this,\'setCommonPrize\','+stage+')">奖励配置</button>' +
        `<button type="button" class="btn btn-outline btn-success" onclick="jackpotBetFunction(${idx1},${idx2},${idx3},${stageIdx})">下注配置</button></td>`;
    html +='</tr>';
    return html;
}


function jackpotBetFunction(idx1, idx2, idx3, idx4){
    var bet = prompt("请输入添加倍率");
    if(bet){
        if($(`#${idx1}_${idx2}_${idx3}_${idx4}_${bet}`).length > 0){
            alert('倍率已存在：'+bet)
            return;
        }
        var html = `<span class="btn btn-outline btn-primary" id="${idx1}_${idx2}_${idx3}_${idx4}_${bet}" onclick="jackpotBetDelFunction(${idx1}, ${idx2}, ${idx3}, ${idx4}, ${bet})">${bet}</span>`;
        $(`.showJackpotBet_${idx1}_${idx2}_${idx3}_${idx4}`).append(html);
        var cur = unescape($(`input[name="jackpot[${idx1}][stages][${idx2}][stages][${idx3}][stages][${idx4}][bet]"]`).val());
        cur = JSON.parse(cur);
        cur.push(bet);
        $(`input[name="jackpot[${idx1}][stages][${idx2}][stages][${idx3}][stages][${idx4}][bet]"]`).val(escape(JSON.stringify(cur)));
    }
}
function jackpotBetDelFunction(idx1, idx2, idx3, idx4, bet){
    bet = bet.toString().replace(/\./g, '\\\.');
    $(`#${idx1}_${idx2}_${idx3}_${idx4}_${bet}`).remove();
    let cur = unescape($(`input[name="jackpot[${idx1}][stages][${idx2}][stages][${idx3}][stages][${idx4}][bet]"]`).val());
    cur = JSON.parse(cur);
    cur = cur.filter(v=>{
        return v!=bet;
    });
    $(`input[name="jackpot[${idx1}][stages][${idx2}][stages][${idx3}][stages][${idx4}][bet]"]`).val(escape(JSON.stringify(cur)));
}

function getJackpotBasicSettingHtml() {
    let openLv = 1;
    let spinsRatio = 1;
    console.log(activity_extra_data)
    if(activity_extra_data.openLv)openLv = activity_extra_data.openLv;
    if(activity_extra_data.spinsRatio)spinsRatio = activity_extra_data.spinsRatio;
    let html = '';
    html +=`<div aria-hidden="true" id="JackpotSetting">
                <div class="form-group">
                    <label class="col-sm-1 control-label">开放等级:</label>
                    <div class="col-sm-1">
                        <input type="text"  name="jackpotOpenLv" value="${openLv}" class="form-control">
                    </div>
                    <div class="col-sm-1">
                        <a target="_blank" class="btn btn-primary " href="#jackpotpro/groups" role="button">概率倍率配置</a>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-1 control-label">体力存量系数（整数）:</label>
                    <div class="col-sm-1">
                        <input type="text"  name="spinsRatio" value="${spinsRatio}" class="form-control">
                    </div>
                </div>
            </div>`
    return html;
}

// prd算法概率配置
function getJackpotPrdSettingHtml() {

    var html = '';
    html += '<table class="jackpotPrdTable table table-bordered">' +
        '<tr><td>任务</td><td>系数1</td><td>系数2</td></tr>'+
        '<tr id="prdOptTr">' +
            '<td colspan="3">' +
                '<button type="button" onclick="addPrdLine()" class="btn btn-primary">添加</button>' +
                '<button type="button" onclick="delPrdLine()" class="btn btn-danger">删除</button>' +
            '</td>' +
        '</tr>'
    html+='</table>'
    html+='</div>';
    return html;
}
function addPrdLine(){
    var idx = $('.prdLine').length + 1
    var html = `
        <tr class="prdLine">
            <td><input  value="${idx}" readonly></td>
            <td><input name="prdConf[${idx}][0]" value="0"></td>
            <td><input name="prdConf[${idx}][1]" value="0"></td>
        </tr>
    `;
    $('#prdOptTr').before(html)
}
function delPrdLine(){
    $('.prdLine:last').remove()
}


function asyncLoadJackpotConfig(i){
    showLoading()
    console.log(activity_extra_data.yStages[i]);
    let asyncData = activity_extra_data.yStages[i]
    let btnsHtml = ''+
    '<button class="btn btn-primary btnAddJackpotYStage" style="" type="button" onclick="addJackpotYStage(this)">添加Y值区间</button>'+
    '<button class="btn btn-danger btnDelJackpotYStage"  style="" type="button" onclick="delJackpotYStage(this)">删除Y值区间</button>' ;

    $('#jackpotLvStageBtnGroup_'+i).empty().append(btnsHtml)
    console.log(asyncData);
    asyncData.stages && $.each(asyncData.stages, function (i0,o0){
        $('#jackpot_lv_table_'+i).find('.btnAddJackpotYStage:last').click()
        $(`input[name="jackpot[${i}][stages][${i0}][start]"]`).val(o0.start)
        $(`input[name="jackpot[${i}][stages][${i0}][end]"]`).val(o0.end)

        o0.stages && $.each(o0.stages,function(i1,o1) {
            $('#jackpot_lv_table_'+i).find('.btnAddJackpotShushuStage:last').click()
            $(`select[name="jackpot[${i}][stages][${i0}][stages][${i1}][shushu][]"]`).val(o1.shushu)
            console.log(o1.stages);
            o1.stages && $.each(o1.stages,function(key,val) {
                // key = val.id
                $('#jackpot_lv_table_'+i).find('.addJackpotNum:last').click()
                $(`select[name="jackpot[${i}][stages][${i0}][stages][${i1}][stages][${key}][taskType]"]`).val(val.taskType)
                $(`input[name="jackpot[${i}][stages][${i0}][stages][${i1}][stages][${key}][id]"]`).val(val.id)
                $(`input[name="jackpot[${i}][stages][${i0}][stages][${i1}][stages][${key}][target]"]`).val(val.target)
                $(`input[name="jackpot[${i}][stages][${i0}][stages][${i1}][stages][${key}][frequency]"]`).val(val.frequency)
                $(`input[name="jackpot[${i}][stages][${i0}][stages][${i1}][stages][${key}][base]"]`).val(val.base)
                $(`input[name="jackpot[${i}][stages][${i0}][stages][${i1}][stages][${key}][mid]"]`).val(val.mid)
                $(`input[name="jackpot[${i}][stages][${i0}][stages][${i1}][stages][${key}][high]"]`).val(val.high)
                var jackpotPrizeHtml = ''
                val.prize && $.each(val.prize, function(ip,op){
                    jackpotPrizeHtml += chestPropsHtml(op)
                })
                $('#jackpot_lv_table_'+i).find('.prizeShow:last').html(jackpotPrizeHtml)
                $(`input[name="jackpot[${i}][stages][${i0}][stages][${i1}][stages][${key}][prize]"]`).val(escape(JSON.stringify(val.prize)))

                var jackpotBetHtml = ''
                val.bet && $.each(val.bet, function(ib,bet){
                    jackpotBetHtml += `<span class="btn btn-outline btn-primary" id="${i}_${i0}_${i1}_${key}_${bet}" onclick="jackpotBetDelFunction(${i}, ${i0}, ${i1}, ${key}, ${bet})">${bet}</span>`;
                })
                $('#jackpot_lv_table_'+i).find('.betShow:last').html(jackpotBetHtml)
                $(`input[name="jackpot[${i}][stages][${i0}][stages][${i1}][stages][${key}][bet]"]`).val(escape(JSON.stringify(val.bet)))
            });
        });
    })
    $('.select2').select2({})
    if($('.asyncLoadConfigBtn').length < 1){
        $('#submitBtn').show();
    }
    hideLoading()
}