let ClubFarmStarCnt = 0;
let ClubFarmRankStages = {}
let AllClubFarmRankStages = 0

function initReward_clubFarm(type) {
    console.log('init ' + type)
    changetypeTo_clubFarm()

    // 奖励回写
    console.log('activity_extra_data:', activity_extra_data)
    if (!activity_extra_data) {
        return
    }
    const reward_conf = activity_extra_data
    $(`input[name="clubFarmConf[preTimes]"]`).val(reward_conf['preTimes'])

    for (const field in reward_conf['score_config']) {
        $(`input[name="clubFarmConf[score_config][${field}]"]`).val(reward_conf['score_config'][field])
    }

    for (const field in reward_conf['club_rank']) {
        $('.addAllClubFarmRankRewardTrBtn:last').click()

        $(`input[name="clubFarmConf[club_rank][${field}][prizes]"]`).val(escape(JSON.stringify(reward_conf['club_rank'][field]['prizes'])))

        let prizeHtml = ''
        $.each(reward_conf['club_rank'][field]['prizes'], function (i, prize) {
            prizeHtml += chestPropsHtml(prize)
        })

        $(`.init_rank_reward_` + field + ":last").html(prizeHtml)
    }

    reward_conf['intervals'] && $.each(reward_conf['intervals'], function (starIdx, item) {
        $('#addClubFarmStarWrapBtn').click()
        $(`input[name="clubFarmConf[intervals][${starIdx}][start]"]`).val(item.start)
        $(`input[name="clubFarmConf[intervals][${starIdx}][end]"]`).val(item.end)
        $(`input[name="clubFarmConf[intervals][${starIdx}][min_scores]"]`).val(item['min_scores'])

        item['farmland_config'] && $.each(item['farmland_config'], function (fieldIdx, fieldItem) {
            $.each(fieldItem['fields'], function (subFieldIdx, subFieldItem) {
                $(`input[name="clubFarmConf[intervals][${starIdx}][farmland_config][${fieldIdx}][fields][${subFieldIdx}][target]"]`).val(subFieldItem.target)
                $(`input[name="clubFarmConf[intervals][${starIdx}][farmland_config][${fieldIdx}][fields][${subFieldIdx}][prizes]"]`).val(escape(JSON.stringify(subFieldItem['prizes'])))

                let prizeHtml = ''
                $.each(subFieldItem['prizes'], function (i, prize) {
                    prizeHtml += chestPropsHtml(prize)
                })
                $(".init_field_reward_" + fieldIdx + "_" + subFieldIdx + ":last").html(prizeHtml)
            })
        })

        item['user_rank'] && $.each(item['user_rank'], function (rankIdx, rankItem) {
            $('.addClubFarmRankRewardTrBtn:last').click()

            $(`input[name="clubFarmConf[intervals][${starIdx}][user_rank][${rankIdx}][prizes]"]`).val(escape(JSON.stringify(rankItem['prizes'])))

            let prizeHtml = ''
            $.each(rankItem.prizes, function (i, prize) {
                prizeHtml += chestPropsHtml(prize)
            })

            $(`.init_rank_reward_` + rankIdx + ":last").html(prizeHtml)
        })

        $(`input[name="clubFarmConf[intervals][${starIdx}][big_reward][prizes]"]`).val(escape(JSON.stringify(item['big_reward']['prizes'])))

        let prizeHtml = ''
        item['big_reward']['prizes'] && $.each(item['big_reward']['prizes'], function (i, prize) {
            prizeHtml += chestPropsHtml(prize)
        })
        $(`.prizeShow:last`).html(prizeHtml)

    })
}

function changetypeTo_clubFarm() {
    $("#reward_info").empty();
    initClubFarmWrap();
}

function initClubFarmWrap() {
    ClubFarmStarCnt = 0;
    ClubFarmRankStages = {}

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

function ClubFarmWrapStageTable() {
    return `
        <div class="form-group" >
            <label class="col-xs-1 control-label">提前预告时长:</label>
            <div class="col-sm-1">
                <input type="text"  name="clubFarmConf[preTimes]" value="" class="form-control">
            </div>
            <div class="col-sm-1">
                <span>(秒)</span>
            </div>
        </div>
        <div class="form-group text-center" >
            <h4 style="font-weight: bold" class="text-left">收集基础值配置*:</h4>
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <td>触发事件</td>
                        <td>普通偷</td>
                        <td>完美偷</td>
                        <td>打成功</td>
                        <td>打到盾</td>
                    <tr>
                </thead>
                <tr>
                    <td>基础积分值</td>
                    <td><input type="number" placeholder="" name="clubFarmConf[score_config][steal_success]" value="0" class="form-control"></td>
                    <td><input type="number" placeholder="" name="clubFarmConf[score_config][steal_break]" value="0" class="form-control"></td>
                    <td><input type="number" placeholder="" name="clubFarmConf[score_config][attack_success]" value="0" class="form-control"></td>
                    <td><input type="number" placeholder="" name="clubFarmConf[score_config][attack_break]" value="0" class="form-control"></td>
                </tr>
            </table>
        </div>
        <div class="form-group text-center" >
            <h4 style="font-weight: bold" class="text-left">公会排名配置*:</h4>
            <table class="table table-bordered">
                <thead>
                <tr>
                    <th width="120">排名</th>
                    <th>奖励</th>
                    <th width="120">奖励配置</th>
                </tr>
                </thead>
                <tbody id="AllClubFarmRankReward"></tbody>
                <tr>
                    <td colspan="7">
                        <div class="text-center" style="margin-top: 20px">
                            <botton class="btn btn-primary addAllClubFarmRankRewardTrBtn" onclick="addAllClubFarmRankRewardTr()">添加</botton>
                            <botton class="btn btn-danger del-tr" onclick="delAllClubFarmRankRewardTr()">删除</botton>
                        </div>
                    </td>
                </tr>
            </table>
        </div>
        <div class="form-group text-center">
            <h4 style="font-weight: bold" class="text-left">奖励配置*:</h4>
            <button class="btn btn-primary" id="addClubFarmStarWrapBtn" onclick="addClubFarmStarWrap(this)" type="button">添加星星层级</button>
            <button class="btn btn-white"  onclick="delClubFarmStarWrap()" type="button">删除星星层级</button>
        </div>
        <hr style=" height:2px;border:none;border-top:2px dotted #0b0;">
        `
}

function addClubFarmStarWrap(obj) {
    const idx = ClubFarmStarCnt++
    ClubFarmRankStages[idx] = 0

    // 田地配置
    const fieldHtml = getFieldHtml(idx, 5);

    let html = `
        <div class="form-group text-left" id="ClubFarmStarWrap_${idx}" data-idx="${idx}" style="margin:10px;padding:5px;border:solid 1px black;">
            <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="clubFarmConf[intervals][${idx}][start]" value="0">
                    <span class="input-group-addon">-</span>
                    <input type="number" style="text-align: center" class="form-control" name="clubFarmConf[intervals][${idx}][end]" value="0">
                </div>
            </div>   
            <div class="form-group">
                <label class="col-sm-1 control-label m-b">用户领奖门槛值: </label>
                <div class="col-sm-2">
                    <input type="number" style="text-align: center" class="form-control" name="clubFarmConf[intervals][${idx}][min_scores]" value="0">
                </div>
            </div>
            <hr style="border:solid 1px black;">

            <div class="form-group">
                <label class="col-sm-1 control-label m-b">田地配置: </label>
            </div>
            
            <div style="margin:10px;padding:5px;border:solid 1px goldenrod;">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th width="120">Index</th>
                            <th width="120">农场编号</th>
                            <th width="120">菜地编号</th>
                            <th>目标值</th>
                            <th>奖励</th>
                            <th width="120">奖励设置</th>
                        </tr>
                    </thead>
                    <tbody>${fieldHtml}</tbody>
                </table>
            </div>
            
            <div class="form-group">
                <label class="col-sm-1 control-label m-b">排行配置: </label>
            </div>
            <div class="ClubFarmRankWrap" id="ClubFarmRankWrap_${idx}" data-idx="${idx}" style="margin:10px;padding:5px;border:solid 1px goldenrod;">
                <table class="table table-bordered">
                    <thead>
                    <tr>
                        <th width="120">排名</th>
                        <th>奖励</th>
                        <th width="120">奖励配置</th>
                    </tr>
                    </thead>
                    <tbody id="ClubFarmRankReward_${idx}"></tbody>
                    <tr>
                        <td colspan="7">
                            <div class="text-center" style="margin-top: 20px">
                                <botton class="btn btn-primary addClubFarmRankRewardTrBtn" onclick="addClubFarmRankRewardTr(this)">添加</botton>
                                <botton class="btn btn-danger del-tr" onclick="delClubFarmRankRewardTr(${idx})">删除</botton>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
            <div class="form-group">
                <label class="col-sm-1 control-label m-b">大奖配置: </label>
            </div>
            <div style="margin:10px;padding:5px;border:solid 1px goldenrod;">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>奖励</th>
                            <th width="120">奖励设置</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr class="commonStageRewardTr">
                            <td class="prizeShow"></td>
                            <td>
                                <input type="hidden" class="prizeInput" name="clubFarmConf[intervals][${idx}][big_reward][prizes]" value="{}">
                                <button type="button" class="btn btn-outline btn-success" onclick="setPrize(this,'setCommonPrize',1)">奖励配置</button>
                            </td>
                        </tr>  
                    </tbody>
                </table>
            </div>
        </div>
        `
    $(obj).before(html)
}

function delClubFarmStarWrap() {
    if (ClubFarmStarCnt < 1) {
        return;
    }
    ClubFarmStarCnt--;
    $('#ClubFarmStarWrap_' + ClubFarmStarCnt).remove();
}

function getFieldHtml(starIdx, len) {

    let html = ""
    for (let i = 0; i < len; i++) {
        html += getSubFieldHtml(starIdx, i, 3)
    }
    return html
}

function getSubFieldHtml(starIdx, idx, len) {

    let html = ""
    for (let i = 0; i < len; i++) {
        html += `
        <tr class="commonStageRewardTr">
            <td width="120"><input type="text" class="form-control" value="${idx * len + i + 1}" readonly ></td>
            <td width="120"><input type="text" class="form-control" value="${idx}" readonly ></td>
            <td width="120"><input type="text" class="form-control" value="${i}" readonly ></td>
            <td><input name="clubFarmConf[intervals][${starIdx}][farmland_config][${idx}][fields][${i}][target]" type="number"  class="form-control" value="0"></td>
            <td class="prizeShow init_field_reward_${idx}_${i}"></td>
            <td>
                <input type="hidden" class="prizeInput" name="clubFarmConf[intervals][${starIdx}][farmland_config][${idx}][fields][${i}][prizes]" value="{}">
                <button type="button" class="btn btn-outline btn-success" onclick="setPrize(this,'setCommonPrize',1)">奖励配置</button>
            </td>
        </tr>`;
    }
    return html
}

function addClubFarmRankRewardTr(obj) {
    let starIdx = $(obj).parents('.ClubFarmRankWrap').data('idx')

    const rankIdx = ClubFarmRankStages[starIdx]++

    const html = `
    <tr class="ClubFarmRankInfoTr commonStageRewardTr ">
        <td width="120"><input type="text" class="form-control" value="${rankIdx + 1}" readonly ></td>
        <td class="prizeShow init_rank_reward_${rankIdx}"></td>
        <td>
            <input type="hidden" class="prizeInput" name="clubFarmConf[intervals][${starIdx}][user_rank][${rankIdx}][prizes]" value="{}">
            <button type="button" class="btn btn-outline btn-success" onclick="setPrize(this,'setCommonPrize',1)">奖励配置</button>
        </td>
    </tr>`
    $("#ClubFarmRankReward_" + starIdx).append(html);
}

function delClubFarmRankRewardTr(starIdx) {

    if (ClubFarmRankStages[starIdx] < 1) {
        return;
    }

    ClubFarmRankStages[starIdx]--;
    $("#ClubFarmStarWrap_" + starIdx).find('.ClubFarmRankInfoTr:last').remove()
}


function addAllClubFarmRankRewardTr() {

    const rankIdx = AllClubFarmRankStages++

    const html = `
    <tr class="AllClubFarmRankInfoTr commonStageRewardTr ">
        <td width="120"><input type="text" class="form-control" value="${rankIdx + 1}" readonly ></td>
        <td class="prizeShow init_rank_reward_${rankIdx}"></td>
        <td>
            <input type="hidden" class="prizeInput" name="clubFarmConf[club_rank][${rankIdx}][prizes]" value="{}">
            <button type="button" class="btn btn-outline btn-success" onclick="setPrize(this,'setCommonPrize',1)">奖励配置</button>
        </td>
    </tr>`
    $("#AllClubFarmRankReward").append(html);
}

function delAllClubFarmRankRewardTr() {

    if (AllClubFarmRankStages < 1) {
        return;
    }

    AllClubFarmRankStages--;
    $("#AllClubFarmRankReward").find('.AllClubFarmRankInfoTr:last').remove()
}