let luckyDiceLvStagesCnt = 0;
let luckyDiceYStageArr = [];
let luckyDiceStagesArr = [];
let luckyDiceShushuArr = [];
let oneLuckyDiceStageReward = {};

function initReward_luckyDice(type) {
    console.log('init ' + type)
    changeTypeTo_luckyDice()

    // 奖励回写
    console.log('activity_extra_data', activity_extra_data)
    console.log('extra_reward', extra_reward)
    console.log('reward_info', reward_info)

    activity_extra_data && $.each(activity_extra_data, function (filed, fv) {
        if (filed === "resultMul") {
            fv && $.each(fv, function (idx, v) {
                $(`input[name="luckyDiceConf[extraConf][resultMul][${idx}][mul]"]`).val(v.mul)
            })
        } else {
            $(`input[name="luckyDiceConf[extraConf][${filed}]"]`).val(fv)
        }
    })

    extra_reward.prdConf && $.each(extra_reward.prdConf, function (idx, prd) {
        addPrdLine();
        $(`input[name="luckyDiceConf[prdConf][${idx}][0]`).val(prd[0])
        $(`input[name="luckyDiceConf[prdConf][${idx}][1]`).val(prd[1])
    })

    reward_info && $.each(reward_info, function (lvIdx, lvStage) {
        $('#btnAddLuckyDiceLvStage').click()
        $(`input[name="luckyDiceConf[rewardConf][${lvIdx}][start]"]`).val(lvStage.start)
        $(`input[name="luckyDiceConf[rewardConf][${lvIdx}][end]"]`).val(lvStage.end)
        lvStage.stages && $.each(lvStage.stages, function (yIdx, yStage) {
            $('.btnAddLuckyDiceYStage:last').click()
            $(`input[name="luckyDiceConf[rewardConf][${lvIdx}][stages][${yIdx}][start]"]`).val(yStage.start)
            $(`input[name="luckyDiceConf[rewardConf][${lvIdx}][stages][${yIdx}][end]"]`).val(yStage.end)
            yStage.stages && $.each(yStage.stages, function (ssIdx, ssStage) {
                $('.btnAddLuckyDiceShushuStage:last').click()
                console.log(luckyDiceStagesArr)
                $(`select[name="luckyDiceConf[rewardConf][${lvIdx}][stages][${yIdx}][stages][${ssIdx}][shushu][]`).val(ssStage.shushu)
                ssStage.stages && $.each(ssStage.stages, function (stageIdx, info) {
                    oneLuckyDiceStageReward = info
                    $('.addLuckyDiceNum:last').click()
                });
            });
        })
    })


}

function changeTypeTo_luckyDice() {
    $("#reward_info").empty()

    initLuckyDiceWrap()
}

function initLuckyDiceWrap() {
    luckyDiceLvStagesCnt = 0;
    luckyDiceYStageArr = [];
    luckyDiceStagesArr = [];
    luckyDiceShushuArr = [];

    let html = LuckyDiceWrapStageTable();
    $("#reward_info").append(html);
}

function LuckyDiceWrapStageTable() {

    return `
        <div class="form-group" >
            <label class="col-xs-1 control-label">开放等级:</label>
            <div class="col-sm-1">
                <input type="number" name="luckyDiceConf[extraConf][openLv]" value="" class="form-control">
            </div>
        </div>
        <div class="form-group" >
            <label class="col-xs-1 control-label">体力存量系数:</label>
            <div class="col-sm-1">
                <input type="number" name="luckyDiceConf[extraConf][spinsRatio]" value="" class="form-control">
            </div>
            <div class="col-sm-1">
                <span>(整数)</span>
            </div>
        </div>
        <div class="form-group" >
            <label class="col-xs-1 control-label">奖励倍数配置:</label>
            <div class="text-center col-sm-6">
                <table class="table table-bordered ">
                    <thead>
                        <tr>
                            <td>结果</td>
                            <td>豹子</td>
                            <td>顺子</td>
                            <td>对子</td>
                        <tr>
                    </thead>
                    <tr>
                        <td>倍数</td>
                        <input type="hidden" placeholder="" name="luckyDiceConf[extraConf][resultMul][0][type]" value="AAA" class="form-control">
                        <td><input type="number" placeholder="" name="luckyDiceConf[extraConf][resultMul][0][mul]" value="0" class="form-control"></td>
                        <input type="hidden" placeholder="" name="luckyDiceConf[extraConf][resultMul][1][type]" value="ABC" class="form-control">
                        <td><input type="number" placeholder="" name="luckyDiceConf[extraConf][resultMul][1][mul]" value="0" class="form-control"></td>
                        <input type="hidden" placeholder="" name="luckyDiceConf[extraConf][resultMul][2][type]" value="AA" class="form-control">
                        <td><input type="number" placeholder="" name="luckyDiceConf[extraConf][resultMul][2][mul]" value="0" class="form-control"></td>
                    </tr>
                </table>
            </div>
        </div>
        <div class="form-group" >
            <label class="col-xs-1 control-label">Prd系数配置:</label>
            <div class="text-center col-sm-6">
                <table class="table table-bordered ">
                    <thead>
                        <tr>
                            <td style="width: 100px">任务</td>
                            <td>系数1</td>
                            <td>系数2</td>
                        <tr>
                    </thead>
                    <tbody id="prdOptTr"></tbody>
                    <tr>
                        <td colspan="5">
                            <div class="text-center" style="margin-top: 20px">
                                <button type="button" onclick="addPrdLine()" class="btn btn-primary">添加</button>
                                <button type="button" onclick="delPrdLine()" class="btn btn-danger">删除</button>
                            </div>
                        </td>
                    </tr>
                    </tr>
                </table>
            </div>
        </div>
        
        <div class="form-group text-center" id="luckyDice_table_wrap">
            <h4 style="font-weight: bold" class="text-left">奖励配置*:</h4>
            <button class="btn btn-primary" id="btnAddLuckyDiceLvStage"  type="button" onclick="addLuckyDiceLvStage(this)">添加等级区间</button>
            <button class="btn btn-danger"   type="button" onclick="delLuckyDiceLvStage(this)">删除等级区间</button>
        </div>
        <hr style=" height:2px;border:none;border-top:2px dotted #0b0;">
    `
}

// 添加第一层级 等级区间
function addLuckyDiceLvStage(obj) {
    const idx = ++luckyDiceLvStagesCnt
    luckyDiceYStageArr[idx] = 0

    let html = `
            <div class="form-group text-left luckyDice_lv_table" data-idx="${idx}" id="luckyDice_lv_table_${idx}" style="margin:10px;padding:5px;border: 1px outset #409eff; border-radius: 5px;">
                <div class="form-group">
                    <label class="col-sm-1 control-label m-b">等级区间: </label>
                    <div class="col-sm-3 input-group">
                        <input type="number" style="text-align: center" class="form-control" name="luckyDiceConf[rewardConf][${idx}][start]" value="0">
                        <span class="input-group-addon">-</span>
                        <input type="number" style="text-align: center" class="form-control" name="luckyDiceConf[rewardConf][${idx}][end]" value="0">
                    </div>
                </div>  
                <hr style="border:solid 1px black;">
                <div class="row text-center" id="luckyDiceLvStageBtnGroup_${idx}" style="padding: 0 30px">
                    <button class="btn btn-primary btnAddLuckyDiceYStage" style="" type="button" onclick="addLuckyDiceYStage(this)">添加Y值区间</button>
                    <button class="btn btn-danger btnDelLuckyDiceYStage"  style="" type="button" onclick="delLuckyDiceYStage(this)">删除Y值区间</button> 
                </div>
            </div>
    `;


    $(obj).before(html)
}


function delLuckyDiceLvStage(obj) {
    if (luckyDiceLvStagesCnt > 0) {
        luckyDiceStagesArr[luckyDiceLvStagesCnt] = 0;
        luckyDiceLvStagesCnt--;
        $('#luckyDice_table_wrap').find('.luckyDice_lv_table:last').remove()
    }
}

// 添加第二层级 Y值区间
function addLuckyDiceYStage(obj) {
    let lvIdx = $(obj).parents('.luckyDice_lv_table').data('idx')
    let yIdx = ++luckyDiceYStageArr[lvIdx];
    let yLvIdx = `${lvIdx}_${yIdx}`;
    luckyDiceShushuArr[yLvIdx] = 0;

    let html = `
            <div class="form-group luckyDice_y_table" data-idx="${yIdx}" id="luckyDice_y_table_${yLvIdx}" style="margin:10px;padding:5px;border: 1px outset #409eff; border-radius: 5px;">
                <div class="form-group">
                    <label class="col-sm-1 control-label m-b">Y值区间: </label>
                    <div class="col-sm-3 input-group">
                        <input type="number" style="text-align: center" class="form-control" name="luckyDiceConf[rewardConf][${lvIdx}][stages][${yIdx}][start]" value="0">
                        <span class="input-group-addon">-</span>
                        <input type="number" style="text-align: center" class="form-control" name="luckyDiceConf[rewardConf][${lvIdx}][stages][${yIdx}][end]" value="0">
                    </div>
                </div>  
                <hr style="border:solid 1px black;">
                <div class="row " id="luckyDiceShushuStageBtnGroup_${yLvIdx}" style="padding: 0 30px">
                    <button class="btn btn-primary btnAddLuckyDiceShushuStage" style="" type="button" onclick="addLuckyDiceShushuStage(this)">添加数数区间</button>
                    <button class="btn btn-danger btnDelLuckyDiceShushuStage"  style="" type="button" onclick="delLuckyDiceShushuStage(this)">删除数数区间</button>
                </div>
            </div>
    `;

    $(obj).before(html)
}

function delLuckyDiceYStage(obj) {
    let lvIdx = $(obj).parents('.luckyDice_lv_table').data('idx');
    if (luckyDiceYStageArr[lvIdx] > 0) {
        let yIdx = luckyDiceYStageArr[lvIdx]--;
        let yLvIdx = `${lvIdx}_${yIdx}`;
        luckyDiceShushuArr[yLvIdx] = 0;
        $(obj).parents('.luckyDice_lv_table').find('.luckyDice_y_table:last').remove()
    }
}


// 添加数数分组层级
function addLuckyDiceShushuStage(obj) {
    let lvIdx = $(obj).parents('.luckyDice_lv_table').data('idx')
    let yIdx = $(obj).parents('.luckyDice_y_table').data('idx')
    let yLvIdx = `${lvIdx}_${yIdx}`;
    let ssIdx = ++luckyDiceShushuArr[yLvIdx]
    let rewardIdx = `${lvIdx}_${yIdx}_${ssIdx}`;
    luckyDiceStagesArr[rewardIdx] = 0;
    let shushuOptions = getShushuSelectorOptions()

    let html = `
        <div class="form-group luckyDice_shushu_table" data-idx="${ssIdx}" id="luckyDice_shushu_table_${lvIdx}_${yIdx}_${ssIdx}" style="margin:10px;padding:5px;border: 1px outset #409eff; border-radius: 5px;">
            <table class="table table-bordered" style="margin: 15px">
            <thead>
                <tr>
                    <td colspan="6"> 
                        <div class="form-group">
                            <label class="col-sm-1 control-label m-b">数数分组 </label>
                            <div class="col-sm-3 input-group"> 
                                <select class=" select2" name="luckyDiceConf[rewardConf][${lvIdx}][stages][${yIdx}][stages][${ssIdx}][shushu][]" multiple  style="min-width: 100%"> 
                                    ${shushuOptions}
                                </select> 
                            </div>
                        </div> 
                    </td>
                </tr> 
                <tr><th>ID</th><th>任务类型</th><th>任务值</th><th>下注值</th><th>奖励</th><th>操作</th></tr>
            </thead>
            <tbody class="table_body_luckyDice"></tbody>
            <tr>
                <td colspan="6">
                    <div class="text-center">
                        <botton class="btn btn-primary addLuckyDiceNum" onclick="addLuckyDiceNum(this)">添加</botton>
                        <botton class="btn btn-danger del-tr" onclick="delLuckyDiceNum(this)">删除</botton>
                    </div>
                </td>
            </tr>
            </table>
        </div>
`;
    $(obj).parent('.row').before(html)
    $('.select2').select2({})
}

function delLuckyDiceShushuStage(obj) {
    let lvIdx = $(obj).parents('.luckyDice_lv_table').data('idx');
    let yIdx = $(obj).parents('.luckyDice_y_table').data('idx');
    let yLvIdx = `${lvIdx}_${yIdx}`;
    if (luckyDiceShushuArr[yLvIdx] < 1) return;
    let ssIdx = luckyDiceShushuArr[yLvIdx]--
    let rewardIdx = `${lvIdx}_${yIdx}_${ssIdx}`;
    luckyDiceStagesArr[rewardIdx] = 0;
    $(obj).parents('.luckyDice_y_table').find('.luckyDice_shushu_table:last').remove();
}

function addLuckyDiceNum(obj) {
    let lvIdx = $(obj).parents('.luckyDice_lv_table').data('idx')
    let yIdx = $(obj).parents('.luckyDice_y_table').data('idx')
    let ssIdx = $(obj).parents('.luckyDice_shushu_table').data('idx')

    let data = oneLuckyDiceStageReward ?? {"id": stageIdx, "taskType": 1, "target": 0};
    oneLuckyDiceStageReward = {}
    let html = luckyDiceTableTR(lvIdx, yIdx, ssIdx, data);
    $(obj).parents('.luckyDice_shushu_table').find('.table_body_luckyDice').append(html);
}

//删排行奖励行
function delLuckyDiceNum(obj) {
    let lvIdx = $(obj).parents('.luckyDice_lv_table').data('idx')
    let yIdx = $(obj).parents('.luckyDice_y_table').data('idx')
    let ssIdx = $(obj).parents('.luckyDice_shushu_table').data('idx')
    let rewardIdx = `${lvIdx}_${yIdx}_${ssIdx}`;
    if (luckyDiceStagesArr[rewardIdx] > 0) {
        $(obj).parents('.luckyDice_shushu_table').find('.table_body_luckyDice').find('tr:last').remove();
        luckyDiceStagesArr[rewardIdx]--;
    }
}

//奖励阶段行数据html
function luckyDiceTableTR(idx1, idx2, idx3, data) {
    let rewardIdx = `${idx1}_${idx2}_${idx3}`;
    let stageIdx = luckyDiceStagesArr[rewardIdx]++;

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

    const betHtml = (idx1, idx2, idx3, stageIdx) => {
        if (bet_show_arr.length <= 0) {
            return ""
        }

        let html = ""
        for (let i = 0; i < bet_show_arr.length; i++) {
            let tempBet = bet_show_arr[i];
            html += `<span style="margin-right: 2px" class="btn btn-outline btn-primary" id="${idx1}_${idx2}_${idx3}_${stageIdx}_${tempBet}" onclick="betDelFunction(${idx1},${idx2},${idx3},${stageIdx},${tempBet})">${tempBet}</span>`;
        }

        return html
    }

    let taskTypeArr = {1: "投掷骰子", 2: "获得金币", 3: "HUGE WIN"};
    const optionHtml = function (type) {
        let html = ``;
        for (let key in taskTypeArr) {
            let tStr = "";
            if (Number(key) === type) {
                tStr = "selected";
            }
            html += `<option ${tStr} value="${key}" >${taskTypeArr[key]}</option>`
        }
        return html
    }

    let rewardStr = !isUnDef(data['prize']) ? JSON.stringify(data['prize']) : '{}';
    let reward = JSON.parse(rewardStr);
    rewardStr = escape(rewardStr)
    const prizeHtml = (() => {
        if (reward.length <= 0) {
            return ""
        }
        let html = ""
        for (let i = 0; i < reward.length; i++) {
            html += chestPropsHtml(reward[i]);
        }
        return html
    })()


    return `
            <tr id="luckyDiceInfo_${stageIdx}" class="commonStageRewardTr">
                <td style="width: 5%;">
                    <input type="text" class="form-control " name="luckyDiceConf[rewardConf][${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][id]" value="${stageIdx + 1}" readonly>
                </td>
                <td style="width: 10%;">
                    <select class="form-control" name="luckyDiceConf[rewardConf][${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][taskType]">${optionHtml(data['taskType'])}</select>
                </td>
                <td style="width: 10%;">
                    <input type="text" class="form-control" name="luckyDiceConf[rewardConf][${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][target]" value="${data['target']}">
                </td>
                
                <td class="betShow  showLuckyDiceBet_${idx1}_${idx2}_${idx3}_${stageIdx}">${betHtml(idx1, idx2, idx3, stageIdx)}</td>
                <td class="prizeShow showLuckyDicePrize_${stageIdx}">${prizeHtml}</td>
                <td style="width: 220px">
                    <input type="hidden" name="luckyDiceConf[rewardConf][${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][bet]" value="${bet}">
                    <button type="button" class="btn btn-outline btn-success" onclick="betFunction(${idx1},${idx2},${idx3},${stageIdx})">下注配置</button>
                    
                    <input type="hidden" class="prizeInput" name="luckyDiceConf[rewardConf][${idx1}][stages][${idx2}][stages][${idx3}][stages][${stageIdx}][prize]" value="${rewardStr}">
                    <button type="button" class="btn btn-outline btn-success" onclick="setPrize(this,'setCommonPrize',1)">奖励配置</button>
                </td>
            </tr>
    `;
}


function betFunction(idx1, idx2, idx3, idx4) {
    let bet = prompt("请输入添加倍率");
    if (bet) {
        if ($(`#${idx1}_${idx2}_${idx3}_${idx4}_${bet}`).length > 0) {
            alert('倍率已存在：' + bet)
            return;
        }

        let html = `<span class="btn btn-outline btn-primary" id="${idx1}_${idx2}_${idx3}_${idx4}_${bet}" onclick="betDelFunction(${idx1}, ${idx2}, ${idx3}, ${idx4}, ${bet})">${bet}</span>`;
        $(`.showLuckyDiceBet_${idx1}_${idx2}_${idx3}_${idx4}`).append(html);

        const node = $(`input[name="luckyDiceConf[rewardConf][${idx1}][stages][${idx2}][stages][${idx3}][stages][${idx4}][bet]"]`)
        let cur = unescape(node.val());
        cur = JSON.parse(cur);
        cur.push(bet);
        node.val(escape(JSON.stringify(cur)));
    }
}

function betDelFunction(idx1, idx2, idx3, idx4, bet) {
    bet = bet.toString().replace(/\./g, '\\\.');
    $(`#${idx1}_${idx2}_${idx3}_${idx4}_${bet}`).remove();

    const node = $(`input[name="luckyDiceConf[rewardConf][${idx1}][stages][${idx2}][stages][${idx3}][stages][${idx4}][bet]"]`)
    let cur = unescape(node.val());
    cur = JSON.parse(cur);
    cur = cur.filter(v => {
        return v !== bet;
    });
    node.val(escape(JSON.stringify(cur)));
}

function addPrdLine() {
    let idx = $('.prdLine').length + 1
    let html = `
        <tr class="prdLine">
            <td><input type="number" class="form-control" value="${idx}" readonly></td>
            <td><input type="number" class="form-control" name="luckyDiceConf[prdConf][${idx}][0]" value="0"></td>
            <td><input type="number" class="form-control" name="luckyDiceConf[prdConf][${idx}][1]" value="0"></td>
        </tr>
    `;
    $('#prdOptTr').before(html)
}

function delPrdLine() {
    $('.prdLine:last').remove()
}
