function initTreasureWrap(){
    $("#reward_info").empty()
    commonLineTitles =[
        {"tname":"bouns消耗/倍率","vname":"pro"},
        {"tname":"修正值","vname":"fix"}
    ];

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

    // 金币老虎机水位系数配置  2011-11 弃用
    // $("#reward_info").append(getTreasureWaterSettingHtml());

    // 金币老虎机bouns修正     2011-11 弃用
    // treasureBonusFixed();

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

    $("#reward_info").append(getTreasureHtmlWrap());
}
function initReward_treasure(){
    initTreasureWrap()
    console.log('activity_extra_data',activity_extra_data)
    activity_extra_data.yStages && $.each(activity_extra_data.yStages,function(i, o){
        // $("#treasure_table_wrap").append(getTreasureHtml());
        $('.btnAddTreasureLvStage').click()
        $('#treasure_lv_table_'+i).find('input[name="treasure['+i+'][start]"]').val(o.start)
        $('#treasure_lv_table_'+i).find('input[name="treasure['+i+'][end]"]').val(o.end)

        $('#treasureLvStageBtnGroup_'+i).empty().append('<button class="btn btn-primary asyncLoadConfigBtn" style="" type="button" onclick="asyncLoadTreasureConfig('+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);
        // o1 && $.each(o1, function(i2, o2){
        //     $('input[name="treasureWaterLevelCoefficient['+i1+']['+i2+']"]').val(o2)
        // })
    })
}

function changeTypeTo_treasure() {
    initTreasureWrap()
}
function getTreasureHtmlWrap() {
    treasureLvStagesCnt = 0;
    treasureYStageArr = [];
    treasureStagesArr = [];
    treasureShushuArr = [];
    var html ='';
    html +='<div class="form-group" id="treasure_table_wrap" style="margin:0px;position:relative;padding-bottom: 20px">'+
        '<button class="btn btn-primary btnAddTreasureLvStage"  type="button" onclick="addTreasureLvStage(this)">添加等级区间</button>'+
        '<button class="btn btn-danger"   type="button" onclick="delTreasureLvStage()">删除等级区间</button>'+
        '</div>';

    return html;
}

// 金币老虎机bouns修正
function treasureBonusFixed() {
    $("#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 addTreasureLvStage(obj){
    var html = getTreasureHtml();
    $(obj).before(html)
}
function getTreasureHtml() {
    treasureLvStagesCnt++;
    treasureYStageArr[treasureLvStagesCnt] = 0;
    var html ='';
    html +='<div class="form-group treasure_lv_table" data-idx="'+treasureLvStagesCnt+'" id="treasure_lv_table_'+treasureLvStagesCnt+'" style="margin:0px;padding-bottom: 15px;border:solid 1px;">';
    html +='<div class="row" style="padding: 0 30px"><lable>等级区间：<input name="treasure['+treasureLvStagesCnt+'][start]">~<input name="treasure['+treasureLvStagesCnt+'][end]"></lable></div>';
    html += '<div class="row " id="treasureLvStageBtnGroup_'+treasureLvStagesCnt+'" style="padding: 0 30px">' +
        '<button class="btn btn-primary btnAddTreasureYStage" style="" type="button" onclick="addTreasureYStage(this)">添加Y值区间</button>'+
        '<button class="btn btn-danger btnDelTreasureYStage"  style="" type="button" onclick="delTreasureYStage(this)">删除Y值区间</button>' +
        '</div>'
    html +='</div>';

    return html;
}
function delTreasureLvStage (){
    if(treasureLvStagesCnt > 0){
        treasureStagesArr[treasureLvStagesCnt] = 0;
        treasureLvStagesCnt--;
        $('#treasure_table_wrap').find('.treasure_lv_table:last').remove()
    }
}

// 添加第二层级 Y值区间
function addTreasureYStage(obj) {
    let lvIdx = $(obj).parents('.treasure_lv_table').data('idx')
    let yIdx = ++treasureYStageArr[lvIdx];
    let yLvIdx = `${lvIdx}_${yIdx}`;
    treasureShushuArr[yLvIdx] = 0;
    console.log(lvIdx);
    console.log(yIdx);
    var html ='';
    html +='<div class="form-group treasure_y_table" data-idx="'+yIdx+'" id="treasure_y_table_'+yLvIdx+'" style="margin:0px;padding-bottom: 15px;border:solid 1px;">';
    html +='<div class="row" style="padding: 0 30px"><lable>Y值区间：<input name="treasure['+lvIdx+'][stages]['+yIdx+'][start]">~<input name="treasure['+lvIdx+'][stages]['+yIdx+'][end]"></lable></div>';
    html += '<div class="row " id="treasureShushuStageBtnGroup_'+yLvIdx+'" style="padding: 0 30px">' +
        '<button class="btn btn-primary btnAddTreasureShushuStage" style="" type="button" onclick="addTreasureShushuStage(this)">添加数数区间</button>'+
        '<button class="btn btn-danger btnDelTreasureShushuStage"  style="" type="button" onclick="delTreasureShushuStage(this)">删除数数区间</button>' +
        '</div>'
    html +='</div>';

    $(obj).before(html)
}
function delTreasureYStage (obj){
    let lvIdx = $(obj).parents('.treasure_lv_table').data('idx');
    if(treasureYStageArr[lvIdx] > 0){
        let yIdx = treasureYStageArr[lvIdx]--;
        let yLvIdx = `${lvIdx}_${yIdx}`;
        treasureShushuArr[yLvIdx] = 0;
        $(obj).parents('.treasure_lv_table').find('.treasure_y_table:last').remove()
    }
}


// 添加数数分组层级
function addTreasureShushuStage(obj) {
    let lvIdx = $(obj).parents('.treasure_lv_table').data('idx')
    let yIdx = $(obj).parents('.treasure_y_table').data('idx')
    let yLvIdx = `${lvIdx}_${yIdx}`;
    let ShushuIdx = ++treasureShushuArr[yLvIdx]
    let rewardIdx = `${lvIdx}_${yIdx}_${ShushuIdx}`;
    treasureStagesArr[rewardIdx] = -1;
    var html = generateTreasureShushuHtml(lvIdx, yIdx, ShushuIdx);

    $(obj).parent('.row').before(html)
    $('.select2').select2({})
}
function delTreasureShushuStage(obj) {
    let lvIdx = $(obj).parents('.treasure_lv_table').data('idx');
    let yIdx = $(obj).parents('.treasure_y_table').data('idx');
    let yLvIdx = `${lvIdx}_${yIdx}`;
    if(treasureShushuArr[yLvIdx] < 1)return;
    let shushuIdx = treasureShushuArr[yLvIdx]--
    let rewardIdx = `${lvIdx}_${yIdx}_${shushuIdx}`;
    treasureStagesArr[rewardIdx] = -1;
    $(obj).parents('.treasure_y_table').find('.treasure_shushu_table:last').remove();
}

generateTreasureShushuHtml = (idx1, idx2, idx3) => {
    var html = `
        <div class="form-group treasure_shushu_table" data-idx="${idx3}" id="treasure_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 treasureShushuSelector" name="treasure[${idx1}][stages][${idx2}][stages][${idx3}][shushu][]" multiple>` ;
                    $.each(shushuGroups, function(i,o){
                        html+="<option value='"+i+"'>"+o+"</option>"
                    })
    html += `</select>
        </div>
        <table class="table table-bordered" style="margin: 15px">
        <thead>
        <tr>
        <th>ID</th>
        <th>任务类型</th>
        <th>任务值</th>
        <th>修正频率</th>
        <th>奖励</th
        ><th>下注值</th>
        <th>操作</th>
        </tr>
        </thead>
        <tbody class="table_body_treasure">
        </tbody><tr><td colspan="7"><div class="text-center">
        <botton class="btn btn-primary addTreasureNum" id="addRank" onclick="addTreasureNum(this)">添加</botton>
        <botton class="btn btn-danger del-tr" onclick="delTreasureNum(this)">删除</botton>
        </div></td></tr></table></div>` ;
    return html;
}

function addTreasureNum(obj){
    let lvIdx = $(obj).parents('.treasure_lv_table').data('idx')
    let yIdx = $(obj).parents('.treasure_y_table').data('idx')
    let ShushuIdx = $(obj).parents('.treasure_shushu_table').data('idx')
    let rewardIdx = `${lvIdx}_${yIdx}_${ShushuIdx}`;
    let stageIdx = ++treasureStagesArr[rewardIdx];
    var data ={"id":treasureStagesArr[rewardIdx],"stage":stageIdx,"taskType":1,"target":0,"frequency":50};
    var html = treasureTableTR(lvIdx, yIdx, ShushuIdx, data);
    $(obj).parents('.treasure_shushu_table').find('.table_body_treasure').append(html);
}

//删排行奖励行
function delTreasureNum(obj){
    let lvIdx = $(obj).parents('.treasure_lv_table').data('idx')
    let yIdx = $(obj).parents('.treasure_y_table').data('idx')
    let ShushuIdx = $(obj).parents('.treasure_shushu_table').data('idx')
    let rewardIdx = `${lvIdx}_${yIdx}_${ShushuIdx}`;
    treasureStagesArr[rewardIdx];
    if(treasureStagesArr[rewardIdx]>0){
        $(obj).parents('.treasure_shushu_table').find('.table_body_treasure').find('tr:last').remove();
        treasureStagesArr[rewardIdx]--;
    }
}

//奖励阶段行数据html
function treasureTableTR(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="treasureInfo_'+stageIdx+'" class="commonStageRewardTr">';
    html +=`<td style="width: 5%;"><input type="text" class="form-control " name="treasure[${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][id]" value="${stageIdx+1}" readonly></td>`;
    var taskTypeArr = {1:"下注次数",2:"获得金币",3:"Bonus Wheel"};
    html +=`<td style="width: 10%;"><select class="form-control" name="treasure[${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][taskType]">`;
    for(j=1;j<=3;j++){
        var tStr = "";
        if(j == data['taskType']){
            tStr = "selected";
        }
        html += '<option '+tStr+' value="'+j+'">'+taskTypeArr[j]+'</option>';
    }
    html +='</select></td>';
    html +=`<td style="width: 10%;"><input type="text" class="form-control" name="treasure[${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][target]"    value="${data['target']}"></td>`;
    html +=`<td style="width: 10%;"><input type="text" class="form-control" name="treasure[${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][frequency]" value="${data['frequency']}"></td>`;
    html +='<td class="prizeShow showTreasurePrize_'+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  showTreasureBet_${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="betDelFunction(${idx1},${idx2},${idx3},${stageIdx},${tempBet}>${tempBet}</span>`;
        }
    }
    html +='</td>';
    html +=`<input type="hidden" name="treasure[${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][prize]" value="${reward}" class="prizeInput">`;
    html +=`<input type="hidden" name="treasure[${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="betFunction(${idx1},${idx2},${idx3},${stageIdx})">下注配置</button></td>`;
    html +='</tr>';
    return html;
}





function betFunction(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="betDelFunction(${idx1}, ${idx2}, ${idx3}, ${idx4}, ${bet})">${bet}</span>`;
        $(`.showTreasureBet_${idx1}_${idx2}_${idx3}_${idx4}`).append(html);
        var cur = unescape($(`input[name="treasure[${idx1}][stages][${idx2}][stages][${idx3}][stages][${idx4}][bet]"]`).val());
        cur = JSON.parse(cur);
        cur.push(bet);
        $(`input[name="treasure[${idx1}][stages][${idx2}][stages][${idx3}][stages][${idx4}][bet]"]`).val(escape(JSON.stringify(cur)));
    }
}

function betDelFunction(idx1, idx2, idx3, idx4, bet){
    bet = bet.toString().replace(/\./g, '\\\.');
    $(`#${idx1}_${idx2}_${idx3}_${idx4}_${bet}`).remove();
    var cur = unescape($(`input[name="treasure[${idx1}][stages][${idx2}][stages][${idx3}][stages][${idx4}][bet]"]`).val());
    cur = JSON.parse(cur);
    cur = cur.filter(v=>{
        return v!=bet;
    });
    $(`input[name="treasure[${idx1}][stages][${idx2}][stages][${idx3}][stages][${idx4}][bet]"]`).val(escape(JSON.stringify(cur)));
}

function getTreasureBasicSettingHtml() {
    var openLv = 1;
    var spinsRatio = 1;
    var difficultyDegree = 1;
    var taskDegree = 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;
    if(activity_extra_data.difficultyDegree)difficultyDegree = activity_extra_data.difficultyDegree;
    if(activity_extra_data.taskDegree)taskDegree = activity_extra_data.taskDegree;
    var html = '';
    html +='<div aria-hidden="true" id="TreasureSetting">';

    html +='<div class="form-group">';
    html +='<label class="col-sm-1 control-label">开放等级:</label><div class="col-sm-1"><input type="text"  name="treasureOpenLv" value="'+openLv+'" class="form-control"></div>';
    html +='<div class="col-sm-1"><a target="_blank" class="btn btn-primary " href="#config/treasurepro/" role="button">概率倍率配置</a></div>';
    html +='</div>';

    html +='<div class="form-group">';
    html +='<label class="col-sm-1 control-label">体力存量系数（整数）:</label><div class="col-sm-1"><input type="text"  name="spinsRatio" value="'+spinsRatio+'" class="form-control"></div>';
    html +='</div>';

    // html +='<div class="form-group">';
    // html +='<label class="col-sm-1 control-label">难度系数:</label><div class="col-sm-1"><input type="text"  name="difficultyDegree" value="'+difficultyDegree+'" class="form-control"></div>';
    // html +='</div>';
    //
    // html +='<div class="form-group">';
    // html +='<label class="col-sm-1 control-label">任务值系数:</label><div class="col-sm-1"><input type="text"  name="taskDegree" value="'+taskDegree+'" class="form-control"></div>';
    // html +='</div>';
    html+='</div>';
    return html;
}
// 金币老虎机水位系数配置
function getTreasureWaterSettingHtml() {
    var treasureWaterLevelCoefficientArr = {
        1:'Bonus1',
        2:'Bonus2',
        3:'Bonus3',
        4:'Bonus4',
        5:'Bonus5',
        // 6:'王冠*3',
        // 7:'小王子*2',
        // 8:'狐狸*3',
        // 9:'小王子*3',
    };
    var html = '';
    html +='<div aria-hidden="true" id="TreasureSetting">';

    html += '<table class="treasureWaterLevelCoefficientTable table table-bordered">' +
        '<tr>' +
        '<td rowspan="2" width="100px">老虎机结果</td>'+
        '<td rowspan="2" width="100px">结果倍率</td>'+
        '<td colspan="10">水位系数</td>'+
        '</tr>'+
        '<tr><td>任务1</td><td>任务2</td><td>任务3</td><td>任务4</td><td>任务5</td><td>任务6</td><td>任务7</td><td>任务8</td><td>任务9</td><td>任务10</td></tr>';

    $.each(treasureWaterLevelCoefficientArr, function (i, o){
        html+= '<tr>' +
            '<td>'+ o +'</td>' +
            '<td><input value="0" name="treasureWaterLevelCoefficient['+i+'][0]" style="width:100%;"></td>' +
            '<td><input value="0" name="treasureWaterLevelCoefficient['+i+'][1]" style="width:100%;"></td' +
            '><td><input value="0" name="treasureWaterLevelCoefficient['+i+'][2]" style="width:100%;"></td>' +
            '<td><input value="0" name="treasureWaterLevelCoefficient['+i+'][3]" style="width:100%;"></td>' +
            '<td><input value="0" name="treasureWaterLevelCoefficient['+i+'][4]" style="width:100%;"></td>' +
            '<td><input value="0" name="treasureWaterLevelCoefficient['+i+'][5]" style="width:100%;"></td>' +
            '<td><input value="0" name="treasureWaterLevelCoefficient['+i+'][6]" style="width:100%;"></td>' +
            '<td><input value="0" name="treasureWaterLevelCoefficient['+i+'][7]" style="width:100%;"></td>' +
            '<td><input value="0" name="treasureWaterLevelCoefficient['+i+'][8]" style="width:100%;"></td>' +
            '<td><input value="0" name="treasureWaterLevelCoefficient['+i+'][9]" style="width:100%;"></td>' +
            '<td><input value="0" name="treasureWaterLevelCoefficient['+i+'][10]" style="width:100%;"></td>' +
            '</tr>'
    })
        '</table>'
    html+='</div>';
    return html;
}

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

    var html = '';
    html += '<table class="treasurePrdTable 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 asyncLoadTreasureConfig(i){
    showLoading()
    var asyncData = {}
    $.ajax({
        type: "GET", // 数据提交类型
        url: "activity/getActStageRewardOuterWrap/"+$asyncId+'/'+i, // 发送地址
        data: {}, //发送数据
        async: false, // 是否异步
        success: function(data) { // 成功回调
            if(typeof data == 'string') data = JSON.parse(data);
            asyncData = data.data
        }
    });
    var btnsHtml = ''+
    '<button class="btn btn-primary btnAddTreasureYStage" style="" type="button" onclick="addTreasureYStage(this)">添加Y值区间</button>'+
    '<button class="btn btn-danger btnDelTreasureYStage"  style="" type="button" onclick="delTreasureYStage(this)">删除Y值区间</button>' ;

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

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

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