function initTrafficPermitWrap(){

    $("#reward_info").append(getTrafficPermitHtml());

    $('.select2').select2({})
}

function initTrafficPermitConfig(){
    // 分层级奖励配置
    $("#reward_info").append(getTrafficPermitHtml());

    console.log(reward_pro)
    let taskTypes = [1, 2]
    let permitTypes = {'normal' : '普通版权限', 'special' : '精英版权限'};
    $.each(reward_pro,  function(i, o){
        addTrafficPermitLvWrap()
        $(`input[name="trafficPermit[${i}][lvStart]"]`).val(o.lvStart)
        $(`input[name="trafficPermit[${i}][lvEnd]"]`).val(o.lvEnd)

        // 基础配置
        o.basic && $.each(o.basic, function(k,v){
            $(`input[name="trafficPermit[${i}][basic][${k}]"]`).val(v)
        })

        // 任务
        $.each(taskTypes, function(_, taskType){
            o[`task${taskType}`] && $.each(o[`task${taskType}`], function(it, ot){
                addTrafficPermitTaskNum(i, taskType)
                $(`select[name="trafficPermit[${i}][task${taskType}][${it+1}][type]"]`).val(ot.type)
                $(`input[name="trafficPermit[${i}][task${taskType}][${it+1}][num]"]`).val(ot.num)
                $(`input[name="trafficPermit[${i}][task${taskType}][${it+1}][getNum]"]`).val(ot.getNum)
            })
        })

        // 权限
        $.each(permitTypes, function(permitType, _){
            o.permitRewards && o.permitRewards[permitType] && function (permitRewards) {
                $(`select[name="trafficPermit[${i}][permitRewards][${permitType}][price]"]`).val(permitRewards.price)
                permitRewards.rewards && $.each(permitRewards.rewards, function(pri, pro){
                    addTrafficPermitReward(i, permitType)
                    $(`select[name="trafficPermit[${i}][permitRewards][${permitType}][rewards][${pri}][type]"]`).val(pro.type)
                    $(`input[name="trafficPermit[${i}][permitRewards][${permitType}][rewards][${pri}][value]"]`).val(pro.value)
                })
            }(o.permitRewards[permitType])
        })

        // 弹窗配置
        $(`select[name="trafficPermit[${i}][alertConfig][status]"]`).val(o.alertConfig.status)
        $(`input[name="trafficPermit[${i}][alertConfig][firstStage]"]`).val(o.alertConfig.firstStage)
        $(`input[name="trafficPermit[${i}][alertConfig][intervalStage]"]`).val(o.alertConfig.intervalStage)

        // 额外奖励
        $(`input[name="trafficPermit[${i}][maxRewards][prize]"]`).val(escape(JSON.stringify(o.maxRewards.prize)))
        $(`input[name="trafficPermit[${i}][maxRewards][specialPrize]"]`).val(escape(JSON.stringify(o.maxRewards.specialPrize)))

        $(`#trafficPermitTable_${i}`).find('.free:last').html(prizeListHtml(o.maxRewards.prize))
        $(`#trafficPermitTable_${i}`).find('.paied:last').html(prizeListHtml(o.maxRewards.specialPrize))

        // 等级奖励
        o.levels && $.each(o.levels, function(il,ol){
            addTrafficPermitNum(i)
            $(`input[name="trafficPermit[${i}][levels][${il}][max]"]`).val(ol.max)
            $(`select[name="trafficPermit[${i}][levels][${il}][isGrandPrize]"]`).val(ol.isGrandPrize)
            $(`input[name="trafficPermit[${i}][levels][${il}][prize]"]`).val(escape(JSON.stringify(ol.prize)))
            $(`input[name="trafficPermit[${i}][levels][${il}][specialPrize]"]`).val(escape(JSON.stringify(ol.specialPrize)))
            $(`#trafficPermitTable_${i}`).find('.free:last').html(prizeListHtml(ol.prize))
            $(`#trafficPermitTable_${i}`).find('.paied:last').html(prizeListHtml(ol.specialPrize))

        })


    })

    // 权限配置
    // $("#reward_info").append(trafficPermitRewards());
    $('.select2').select2({})
    let tbody;
    reward_conf && $.each(reward_conf, function(i, o){
        console.log(i,o)
        switch (i){
            case 'normal':tbody = $('#table_body_TrafficPermitRewardsNormal');break;
            case 'special':tbody = $('#table_body_TrafficPermitRewardsSpecial');break;
        }
        $(`select[name="trafficPermit[${lvCnt}][permitRewards][${i}][price]"]`).val(o.price)

        o && o.rewards && $.each(o.rewards, function(i1, o1){
            // console.log(49, i, tbody.next(tbody).find('.addTrafficPermitReward'))
            tbody.next(tbody).find('.addTrafficPermitReward').click()
            tbody.find(`select[name="trafficPermit[${lvCnt}][permitRewards][${i}][rewards][type][]"]:last`).val(o1.type)
            tbody.find(`input[name="trafficPermit[${lvCnt}][permitRewards][${i}][rewards][value][]"]:last`).val(o1.value)
        })
    })

    // 弹窗配置
    // $("#reward_info").append(trafficPermitAlert());
    // reward_conf.alertConfig.alertConfig.status && $(`select[name="trafficPermit[${lvCnt}][alertConfig][status]"]`)..alertConfig.status)
    // reward_conf.alertConfig.alertConfig.firstStage && $(`input[name="trafficPermit[${lvCnt}][alertConfig][firstStage]"]`)..alertConfig.firstStage)
    // reward_conf.alertConfig.alertConfig.intervalStage && $(`input[name="trafficPermit[${lvCnt}][alertConfig][intervalStage]"]`)..alertConfig.intervalStage)
}

function getTrafficPermitSettingHtml(lvCnt) {
    var openLv = 1;
    var guideLv = 1;
    var upLv   = 1;
    var passExp= 3;
    var itemColor= "#FF689896";
    var iconColor= "#FF689896";
    var maxLevelExpGap = 500;
    if($info['extraData'] != undefined && ($info['extraData']['openLv'])){
        openLv = $info['extraData']['openLv'] ? $info['extraData']['openLv'] :  1;
        guideLv = $info['extraData']['guideLv'] ? $info['extraData']['guideLv'] :  1;
        upLv = $info['extraData']['upLvDiamondNum'] ? $info['extraData']['upLvDiamondNum'] :  1;
        passExp = $info['extraData']['passExp'] ? $info['extraData']['passExp'] :  3;
        itemColor = $info['extraData']['itemColor'] ? $info['extraData']['itemColor'] :  "#FF689896";
        iconColor = $info['extraData']['iconColor'] ? $info['extraData']['iconColor'] :  "#FF689896";
        maxLevelExpGap  = $info['extraData']['maxLevelExpGap'] ? $info['extraData']['maxLevelExpGap'] : 500;
    }
    var html = '';
    html +='<div aria-hidden="true" id="TrafficPermitSetting">';
    html +='<div class="form-group">';
    html +=`<label class="col-sm-1 control-label">开放等级:</label><div class="col-sm-1"><input type="text"  name="trafficPermit[${lvCnt}][basic][openLv]" value="`+openLv+'" class="form-control"></div>';
    html +=`<label class="col-sm-1 control-label">指引等级:</label><div class="col-sm-1"><input type="text"  name="trafficPermit[${lvCnt}][basic][guideLv]" value="`+guideLv+'" class="form-control"></div>';
    html +=`<label class="col-sm-1 control-label">提升等级钻石数:</label><div class="col-sm-1"><input type="text"  name="trafficPermit[${lvCnt}][basic][upLvDiamondNum]" value="`+upLv+'" class="form-control"></div>';
    html +=`<label class="col-sm-1 control-label">通行证获得经验:</label><div class="col-sm-1"><input type="text"  name="trafficPermit[${lvCnt}][basic][passExp]" value="`+passExp+'" class="form-control"></div>';
    html +=`<label class="col-sm-1 control-label">扫光颜色:</label><div class="col-sm-1"><input type="text"  name="trafficPermit[${lvCnt}][basic][itemColor]" value="`+itemColor+'" class="form-control"></div>';
    html +=`<label class="col-sm-1 control-label">图标底色:</label><div class="col-sm-1"><input type="text"  name="trafficPermit[${lvCnt}][basic][iconColor]" value="`+iconColor+'" class="form-control"></div>';
    html +=`<label class="col-sm-1 control-label">额外等级经验差:</label><div class="col-sm-1"><input type="text"  name="trafficPermit[${lvCnt}][basic][maxLevelExpGap]" value="`+maxLevelExpGap+'" class="form-control"></div>';
    html +='</div>';
    html+='</div>';
    return html;
}

function getTrafficPermitHtml() {
    console.log(1277777)
    let html =  `
        <hr style=" height:2px;border:none;border-top:2px dotted #0b0;">
        <div class="" id="stageTable" style="top:10px">
            <div class="ibox-title" style="border-top: 0;"><h5 style="font-weight: bold">分层级配置</h5></div>
        </div>
        <div class="form-group " id="lvBtnGroups">
            <div class=" ">
                <button class="btn btn-primary" id="addCollectLvWrapBtn" onclick="addTrafficPermitLvWrap()" type="button">添加等级层级</button>
                <button class="btn btn-white"   id="delCollectLvWrapBtn" onclick="delTrafficPermitLvWrap()" type="button">删除等级层级</button>
            </div>
       </div>
       <hr style=" height:2px;border:none;border-top:2px dotted #0b0;">
    `;
    console.log(13777)
    return html;
}

function addTrafficPermitLvWrap() {
    let lvCnt = $('.trafficPermitLvWrap').length + 1

    // $("#reward_info").append();
    let basicHtml = getTrafficPermitSettingHtml(lvCnt)

    let taskHtml1 = getTrafficPermitTaskHtml(lvCnt, 1)
    let taskHtml2 = getTrafficPermitTaskHtml(lvCnt, 2)
    let permitHtml = trafficPermitRewards(lvCnt)
    let alertHtml = trafficPermitAlert(lvCnt)
    var html =`
        
        <div class="form-group trafficPermitLvWrap" id="trafficPermitTable_${lvCnt}" style="border: 1px solid lightgray;padding: 5px;">
            <div class="form-group">
                <label class="col-sm-1 control-label m-b">等级区间: </label>
                <div class="col-sm-3 input-group">
                    <input type="text" style="text-align: center" class="form-control" name="trafficPermit[${lvCnt}][lvStart]" value="0">
                    <span class="input-group-addon">-</span>
                    <input type="text" style="text-align: center" class="form-control" name="trafficPermit[${lvCnt}][lvEnd]" value="0">
                </div>
            </div>
            ${basicHtml}
            <hr style="border:solid 1px black;">
            ${taskHtml1}
            ${taskHtml2}
            <hr style="border:solid 1px black;">
            ${permitHtml}
            <hr style="border:solid 1px black;">
            ${alertHtml}
            <hr style="border:solid 1px black;">
            <h5 style="font-weight: bold">奖励配置</h5>
            <table class="table table-bordered">
                <thead>
                    <tr><th>等级</th><th>经验值</th><th>大奖</th><th>免费奖励</th><th>令牌奖励</th><th>操作</th></tr>
                </thead>
                <tbody id="trafficPermitTbody_${lvCnt}">
            
                </tbody>
                <tr>
                    <td colspan="6">
                        <div class="text-center">
                            <botton class="btn btn-primary" onclick="addTrafficPermitNum(${lvCnt})">添加</botton>
                            <botton class="btn btn-danger del-tr" onclick="delTrafficPermitNum(${lvCnt})">删除</botton>
                        </div>
                    </td>
                </tr>
            </table>
        </div>`
    console.log($('#lvBtnGroups'));
    $('#lvBtnGroups').before(html)
    $(`#trafficPermitTbody_${lvCnt}`).append(trafficPermitExtraTR(lvCnt));

}
function delTrafficPermitLvWrap() {
    let lvCnt = $('.trafficPermitLvWrap').length
    if(lvCnt > 0){
        $('.trafficPermitLvWrap:last').remove()
    }
    return html;
}

function addTrafficPermitNum(lvCnt) {
    let trafficPermit_limit = $(`#trafficPermitTbody_${lvCnt}`).find('tr').length - 1;
    var html = trafficPermitTR(lvCnt, trafficPermit_limit);
    $(`#trafficPermitTbody_${lvCnt}`).append(html);
}

//删排行奖励行
function delTrafficPermitNum(){
    if(trafficPermit_limit>=0){
        // console.log(reward_limit);
        $("#table_body4").children("tr:last-child").remove();
        trafficPermit_limit--;
    }
}

//奖励阶段行数据html
function trafficPermitExtraTR(lvCnt){
    var rewardDft = escape( '[]');
    var html =`
        <tr class="commonStageRewardTr">
            <td style="width: 5%;"><input type="text" class="form-control"  value="额外" readonly></td>
            <td style="width: 10%;"><input type="text" class="form-control" value="额外等级" readonly></td>
            <td style="width: 15%;">
                <select class="form-control">
                </select>
            </td>
            <td class="free"></td>
            <td class="paied"></td>
            <input type="hidden" class="freeInput" name="trafficPermit[${lvCnt}][maxRewards][prize]" value="${rewardDft}">
            <input type="hidden" class="paiedInput" name="trafficPermit[${lvCnt}][maxRewards][specialPrize]" value="${rewardDft}">
            <td style="width: 15%;">
                <button type="button" class="btn btn-outline btn-success" onclick="setPrize(this,'setCommonPrize2',1,'free')">免费奖励配置</button>
                <button type="button" class="btn btn-outline btn-success" onclick="setPrize(this,'setCommonPrize2',1,'paied')">令牌奖励配置</button>
            </td>
        </tr>`
    return html;
}
//奖励阶段行数据html
function trafficPermitTR(lvCnt, stage = 1){
    var reward = escape('[]');
    var taskTypeArr = {0:"否",1:"是"};
    let options = ''
    for(var j=0;j<=1;j++){
        options += '<option value="'+j+'">'+taskTypeArr[j]+'</option>';
    }
    var html =`
        <tr class="trafficPermitTr commonStageRewardTr" >
        <td style="width: 5%;"><input type="text" class="form-control" name="trafficPermit[${lvCnt}][levels][${stage}][levelId]" value="${stage}" readonly></td>
        <td style="width: 10%;"><input type="text" class="form-control" name="trafficPermit[${lvCnt}][levels][${stage}][max]" value="${stage}"></td>
        <td style="width: 15%;"><select class="form-control" name="trafficPermit[${lvCnt}][levels][${stage}][isGrandPrize]">${options}</select></td>
        <td class="free"></td>
        <td class="paied">
        </td>
        <input type="hidden" class="freeInput" name="trafficPermit[${lvCnt}][levels][${stage}][prize]" value="${reward}">
        <input type="hidden" class="paiedInput" name="trafficPermit[${lvCnt}][levels][${stage}][specialPrize]" value="${reward}">
        <td style="width: 15%;">
                <button type="button" class="btn btn-outline btn-success" onclick="setPrize(this,'setCommonPrize2',1,'free')">免费奖励配置</button>
                <button type="button" class="btn btn-outline btn-success" onclick="setPrize(this,'setCommonPrize2',1,'paied')">令牌奖励配置</button>
        </td>
        </tr>`
    return html;
}

function getTrafficPermitTaskHtml(lvCnt, id) {
    var html ='';
    var text = id == 1?"单日-默认":"双日";
    html +='<div class="" id="trafficPermitTask_table">';
    html +='<div class="ibox-title" style="border-top: 0;"><h5 style="font-weight: bold">通行证任务('+text+')</h5></div>';
    html +='<table class="table table-bordered">';
    html +='<thead><tr><th>任务ID</th><th>任务类型</th><th>达成次数</th><th>获得经验（次）</th></tr></thead>' ;
    html +=`<tbody id="table_body_TrafficPermitTask_${lvCnt}_${id}">`;
    html +=`</tbody>
                <tr>
                    <td colspan="6">
                        <div class="text-center">
                            <botton class="btn btn-primary" onclick="addTrafficPermitTaskNum(${lvCnt}, ${id})">添加</botton>
                            <botton class="btn btn-danger del-tr" onclick="delTrafficPermitTaskNum(${lvCnt}, ${id})">删除</botton>`;
    html +='</div></td></tr></table></div>';
    return html;
}

function addTrafficPermitTaskNum(lvCnt, id) {
    let trafficPermitTask_limit = $(`#table_body_TrafficPermitTask_${lvCnt}_${id}`).find('tr').length + 1
    var data ={"id":trafficPermitTask_limit,"max":1,"num":1,"getNum":1};
    var html = trafficPermitTaskTR(lvCnt, data,id);
    $(`#table_body_TrafficPermitTask_${lvCnt}_${id}`).append(html);
}

function delTrafficPermitTaskNum(lvCnt, id) {
    if($(`#table_body_TrafficPermitTask_${lvCnt}_${id}`).find('tr').length > 0){
        $(`#table_body_TrafficPermitTask_${lvCnt}_${id}`).find('tr:last').remove()
    }
}

function trafficPermitTaskTR(lvCnt, data,type) {
    var name  = `trafficPermit[${lvCnt}][task${type}]`
    var stage = data['id'];
    var html ='';
    html+='<tr id="treasureInfo_'+stage+'">';
    html +='<td style="width: 5%;"><input type="text" class="form-control" name="'+name+'['+stage+'][id]" value="'+stage+'"></td>';
    var taskTypeArr = {
        1:"邀请好友"
        ,2:"完成世界"
        ,3:"偷"
        ,4:"打"
        ,5:"和大盗莫里一起偷袭"
        ,6:"和拳手莫里一起进攻"
        ,7:"转一次黄金转盘"
        ,8:"夺宝一次"
        ,9:"玩一次黄金矿工"
        ,10:"分享游戏"
        ,11:"召回好友"
        ,12:"消耗体力200"
        ,13:"消耗体力800"
        ,14:"消耗体力2000"
        ,15:"消耗体力8000"
    };
    html +='<td style="width: 15%;"><select class="form-control" name="'+name+'['+stage+'][type]">';
    for(var j=1;j<=15;j++){
        var tStr = "";
        if(j == data['type']){
            tStr = "selected";
        }
        html += '<option '+tStr+' value="'+j+'">'+taskTypeArr[j]+'</option>';
    }
    html +='</select></td>';
    html +='<td><input type="text" class="form-control" name="'+name+'['+stage+'][num]" value="'+data['num']+'"></td>';
    html +='<td><input type="text" class="form-control" name="'+name+'['+stage+'][getNum]" value="'+data['getNum']+'"></td>';
    html +='</tr>';
    return html;
}

trafficPermitAlert = (lvCnt)=>{
    let alertSelectorAlert = trafficPermitAlertSelector(lvCnt)
    var html  = `
            <div class="" id="trafficPermitTask_table">
                <div class="ibox-title" style="border-top: 0;">
                    <h5 style="font-weight: bold">通行证弹窗配置</h5>
                </div>
                <table class="table table-bordered">
                    
                        <tr>
                            <td>弹窗开关</td>
                            <td>
                                ${alertSelectorAlert}
                            </td>
                        </tr> 
                        <tr>
                            <td>第一次触发弹窗的通行证等级</td>
                            <td>
                                <input class="form-control" name="trafficPermit[${lvCnt}][alertConfig][firstStage]">
                            </td>
                        </tr>
                        <tr>
                            <td>通行证等级每升满X级就触发一次弹窗</td>
                            <td>
                                <input class="form-control" name="trafficPermit[${lvCnt}][alertConfig][intervalStage]">
                            </td>
                        </tr>
                   
                </table>
            </div>`;
    return html;
}
trafficPermitAlertSelector = (lvCnt)=>{

    let alertSelector = `<select class="form-control select2" name="trafficPermit[${lvCnt}][alertConfig][status]">`;
    alertSelector += `<option value="0">关</option>`;
    alertSelector += `<option value="1">开</option>`;
    alertSelector += '</select>';
    return alertSelector
}
trafficPermitRewards = (lvCnt)=>{
    let priceSelectorNormal = trafficPermitPriceSelector(lvCnt, 'normal')
    let priceSelectorSpecial = trafficPermitPriceSelector(lvCnt, 'special')
    let html  = `
            <div class="" id="trafficPermitTask_table_${lvCnt}">
                <div class="ibox-title" style="border-top: 0;">
                    <h5 style="font-weight: bold">通行证权限</h5>
                </div>
                <table class="table table-bordered">
                   
                    <thead>
                        <tr>
                            <th colspan="2">普通版</th>
                        </tr> 
                        <tr>
                            <th>价格</th>
                            <th>
                                ${priceSelectorNormal}
                                <input type="hidden" name="trafficPermit[${lvCnt}][permitRewards][normal][gid]" value="1770">
                            </th>
                        </tr> 
                        <tr>
                            <th>奖励类型</th>
                            <th>奖励值</th>
                        </tr>
                    </thead>
                    <tbody id="table_body_TrafficPermitRewardsNormal_${lvCnt}">
                    </tbody>
                    <tr class="btnsTr">
                        <td colspan="2">
                            <div class="text-center">
                                <botton class="btn btn-primary addTrafficPermitReward" onclick="addTrafficPermitReward(${lvCnt}, 'normal')">添加</botton>
                                <botton class="btn btn-danger del-tr delTrafficPermitReward" onclick="delTrafficPermitReward(${lvCnt}, 'normal')">删除</botton>
                            </div>
                        </td>
                    </tr>
                    <thead>
                         <tr>
                            <td colspan="2">精英版</td>
                        </tr> 
                        <tr>
                            <td>价格</td>
                            <td>
                                ${priceSelectorSpecial}
                                <input type="hidden" name="trafficPermit[${lvCnt}][permitRewards][special][gid]" value="1814">
                            </td>
                        </tr> 
                        <tr>
                            <th>奖励类型</th>
                            <th>奖励值</th>
                        </tr>
                    </thead>
                    <tbody id="table_body_TrafficPermitRewardsSpecial_${lvCnt}">
                    </tbody>
                    <tr class="btnsTr">
                        <td colspan="2">
                            <div class="text-center">
                                <botton class="btn btn-primary addTrafficPermitReward" onclick="addTrafficPermitReward(${lvCnt}, 'special')">添加</botton>
                                <botton class="btn btn-danger del-tr delTrafficPermitReward" onclick="delTrafficPermitReward(${lvCnt}, 'special')">删除</botton>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>`;
    return html;
}

trafficPermitPriceSelector = (lvCnt, type)=>{

    let priceSelector = `<select class="form-control select2" name="trafficPermit[${lvCnt}][permitRewards][${type}][price]">`;
    $.each(goodSku, function (k, v) {
        priceSelector += `<option value="${v['price']}">${v['price']}</option>`;
    });
    priceSelector += '</select>';
    return priceSelector
}

addTrafficPermitReward = (lvCnt, type) => {
    let tbody = false
    switch (type){
        case 'special':
            tbody = $(`#table_body_TrafficPermitRewardsSpecial_${lvCnt}`);break;
        case 'normal':
            tbody = $(`#table_body_TrafficPermitRewardsNormal_${lvCnt}`);break;
    }
    if(!tbody){
        alert('未知类型：' + type)
        return
    }
    let idx = tbody.find('tr').length
    let rewardsTypes = {
        // 1 :'通行证专属名字颜色',
        2 :'通行证专属头像框',
        3 :'赠送N个通行证等级',
    };
    let ops = `<select class="select2" name="trafficPermit[${lvCnt}][permitRewards][${type}][rewards][${idx}][type]">`
    $.each(rewardsTypes, function (i,o){
        ops += `<option value="${i}">${o}</option>`;
    })
    ops += '</select>'
    let html = `
        <tr>
            <td class="rewardType">${ops}</td>
            <td class="rewardValue"><input class="form-control"  name="trafficPermit[${lvCnt}][permitRewards][${type}][rewards][${idx}][value]" value="0"></td>
        </tr>
    `
    tbody.append(html)
    $('.select2').select2({})

}
delTrafficPermitReward = (lvCnt, type) => {
    let tbody = false
    switch (type){
        case 'special':
            tbody = $(`#table_body_TrafficPermitRewardsSpecial_${lvCnt}`);break;
        case 'normal':
            tbody = $(`#table_body_TrafficPermitRewardsNormal_${lvCnt}`);break;
    }
    if(!tbody){
        alert('未知类型：' + type)
        return
    }
    tbody.find('tr:last').remove()
}