{% extends 'obj_form.html' %}
{% load i18n %}
{% load tj_filters %}
  
    <style>       
        #province,#city{
            padding-left:0px;
            margin-left:0px;
        }       

    </style>

    

    {% block js %}
        {{ block.super }}    

        //$('#obj_form .js-example-basic-multiple').select2({multiple: true});
        //将用户选择移至多选内容的末尾
        
        $("#obj_form .js-example-basic-multiple").on("select2:select", function (evt) {
            var element = evt.params.data.element;
            var $element = $(element);  
            $element.detach();
            $(this).append($element);
            $(this).trigger("change");
        });  

        /*
        $('#batch_label').autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: '/obj/ajax/autocomplete/batch/',
                    dataType: "json",
                    data: {
                        term:   $("#batch_label").val() ,//搜索栏里的内容
                        company_id:  $('#id_company').val() ,//额外参数
                    },
                    success: function(data) {
                        response(data);
                    }
                });
            },
            select: function (event, ui) {
                $("#batch_id").val(ui.item.value);
                $("#batch_label").val(ui.item.label);
                return false;
            }
        });
        */

        $('#interval-start,#interval-end').datetimepicker({datepicker:false,format:'H:i:s'});
        $("#sel-delivery_batches").select2({
            ajax: {
                url : '/obj/ajax/autocomplete/batch/',
                dataType : 'json',   
                //delay : 250,// 延迟显示
                data: function(params){    
                    return{
                        term:   params.term ,//搜索栏里的内容
                        company_id:  $('#id_company').val() ,//额外参数
                        vtype_id:'2',
                    };
                },
                processResults: function (data) {        //data返回数据
                    var options = new Array();                    
                    $(data).each(function(i, o) {
                        options.push({　　　　　　　　　　//获取select2个必要的字段，id与text
                            id : o.value,         
                            text : o.label    
                        });
                    });
                    return {
                        results: options        //返回数据
                    };
                },
                cache: true
            },
            //language: "zh-CN",
            placeholder: "输入批次号搜索...",
            allowClear: true,    //选中之后，可手动点击删除         
            escapeMarkup: function (markup) { return markup; }, // 字符转义处理自定义格式化防止xss注入
            formatResult: function formatRepo(repo){return repo.text;}, // 函数用来渲染结果
            formatSelection: function formatRepoSelection(repo){return repo.text;} // 函数用于呈现当前的选择
        });
        $('.btn-show-timebucket').click(function(){
            var d=JSON.parse($('#id_timebucket').val());
            if($.isEmptyObject(d)){
                $('#timebucket-name').val('');
                $('#tb-timebucket tbody').html('');
            }else{
                $('#tb-timebucket tbody').html('');
                $('#timebucket-name').val(d.name);
                for(var i in d.intervals){
                    $('#tb-timebucket tbody').append(
                        "<tr><td class='t1'>"+d.intervals[i][0]+"</td>"+
                        "<td class='t2'>"+d.intervals[i][1]+"</td>"+
                        "<td><a type='button' class='btn btn-xs btn-danger interval-delete'>删除</a></td></tr>");
                };
            };
            $('#timebucket-modal').modal('show');         
        });      
        $('#timebucket-modal .add-interval').click(function(){    
            var t1=$('#interval-start').val();
            var t2=$('#interval-end').val();
            if($.isEmpty(t1) || $.isEmpty(t2)){
                toastr.error(
                    "时间段开始和结束不能为空！",
                    "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );                
            }else{            
                $('#tb-timebucket tbody').append(
                    "<tr><td class='t1'>"+t1+"</td><td class='t2'>"+t2+"</td>"+
                    "<td><a type='button' class='btn btn-xs btn-danger interval-delete'>删除</a></td></tr>");
            }
        });
        $('#tb-timebucket').on('click', 'a.interval-delete', function(){        
            $(this).closest('tr').remove();
        });        
        $('#timebucket-modal .btn-confirm').click(function(){
            var bk_name=$('#timebucket-name').val();
            var bk_intervals=[],aTm=[],t1='',t2='';            
            $("#tb-timebucket tbody tr").each(function(rowIndex) {   
                t1=$(this).find('.t1').text();
                t2=$(this).find('.t2').text();    
                bk_intervals.push([ t1, t2 ]);
                aTm.push(t1+'至'+t2);
            });   
            if($.isEmpty(bk_name) || bk_intervals.length==0){
                toastr.error(
                    "时间段名称，及时间段开始和结束不能为空！",
                    "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );                  
            }else{
                $('#timebucket-cfg').text(bk_name+" "+aTm.join(' '));
                $('#id_timebucket').val(JSON.stringify({"name":bk_name,"intervals":bk_intervals})); 
                $('#timebucket-modal').modal('hide');                
            };
        });     
        $('#timebucket-modal .btn-clearall').click(function(){
            $('#timebucket-cfg').text("无");
            $('#id_timebucket').val('{}'); 
            $('#timebucket-modal').modal('hide');   
        });
        var intervals=[],s='';
        {% for t in form.instance.timebucket.intervals %}
            intervals.push("{{t.0}}至{{t.1}}");
        {% endfor %}  
        if (intervals.length==0){
            s='无';
        }else{
            s='{{form.instance.timebucket.name}} '+intervals.join(' ');
        };
        $('#timebucket-cfg').text(s);
        //初始化奖项区域限定
        $('#tb_award tbody tr').each(function(){
            var adms=JSON.parse($(this).find('td.awd-adms input').val());
            var sp=$(this).find('td.awd-adms span'),a=[];
            if(adms.length==0){
                $(sp).text('无');
            }else{
                for(var k in adms){
                    a.push(adms[k].name);
                };
                $(sp).text(a.join(','));
            }            
        });
        $('#tb_award tbody').on('click','.btn-adms-cfg',function(){    
            var me=$(this);
            $('#el-id').val($(this).closest('td').find('input').attr('id')); 
            var awd_name=$(me).closest('tr').children('td').eq(1).html();
            $('#adms-modal .modal-content .modal-header h4').text("区域设置："+awd_name);      
            //初始化区域限定列表 
            $('#adms-modal tbody').html('');
            var v=$(this).closest('td').find('input').val();
            if(v!='[]'){
                v=JSON.parse(v);
                var s='';
                for(var i in v){
                    s=s+"<tr adm-id="+v[i].id+" adm-name='"+v[i].name+"'>"+
                        "<td adm-id='"+v[i].lvs.lv1.id+"'>"+v[i].lvs.lv1.name+"</td>"+   
                        "<td adm-id='"+v[i].lvs.lv2.id+"'>"+v[i].lvs.lv2.name+"</td>"+
                        "<td adm-id='"+v[i].lvs.lv3.id+"'>"+v[i].lvs.lv3.name+"</td>"+
                        "<td><a type='button' class='btn btn-xs btn-danger adm-delete'>删除</a></td>"+
                        "</tr>";             
                };
                $('#adms-modal tbody').append(s);
            };
            $('#adms-modal').modal('show'); 
        });
        //区域设置 配置省市县3级联动
        $.ajax({
            
            url: "/gis/adm/1/",
            //2023-01-03
            url: "/utils/adm/ajax/1/",
            
            success: function(data) {
                
                //var me=$('#awd-adm-lv1');
                //$(me).empty();    
                //data=data.result;                
                //console.log(data);
                //$.each(data,function(idx){$(me).append("<option value='"+data[idx].id+"'>"+data[idx].name+"</option>")});
                //$(me).append("<option value='' selected='selected'>---------</option>");

                var html='';
                data=data.result;
                $.each(data,function(idx){
                    html=html+"<option value='"+data[idx].id+"'>"+data[idx].name+"</option>";
                });
                html=html+"<option value='' selected='selected'>---------</option>";
                $('#awd-adm-lv1').append(html);
                $('#province').append(html);    

            },
            dataType: 'json',
            //jsonp: 'callback'
        });       
        $("#awd-adm-lv1").change(function() {  
            $('#awd-adm-lv3').empty().append("<option value='' selected='selected'>---------</option>")
            getCity($(this).val(),$('#awd-adm-lv2'));           
        });
        $("#awd-adm-lv2").change(function() { 
            getCounty($(this).val(),$('#awd-adm-lv3'));
        });        
        $('#adms-modal .dlg-add-adm').click(function(){  
            var id=0,name='',s='';
            if($.isEmpty($('#awd-adm-lv3').val())){                
                if($.isEmpty($('#awd-adm-lv2').val())){
                    if($.isEmpty($('#awd-adm-lv1').val())){   
                        toastr.error(
                            "请选择奖项限定区域！",
                            "操作错误：",
                            {timeOut: 800, positionClass: "toast-center-center"}
                        );         
                        return;               
                    }else{
                        id=$('#awd-adm-lv1').val();
                        name=$('#awd-adm-lv1 option:selected').text();
                        //当前区域是否已在列表中
                        bExists=false;
                        $("#adms-modal tbody tr").each(function(rowIndex) {
                            if($(this).attr('adm_id')==id){
                                bExists=true;  
                                //跳出each循环
                                return false;
                            };
                        });
                        if(bExists){
                            toastr.error(
                                name+"已经在列表中！",
                                "操作错误：",
                                {timeOut: 800, positionClass: "toast-center-center"}
                            );         
                            return;                    
                        }else{
                            s="<tr adm-id="+id+" adm-name='"+name+"'>"+
                                "<td adm-id='"+$('#awd-adm-lv1').val()+"'>"+$('#awd-adm-lv1 option:selected').text()+"</td>"+   
                                "<td adm-id='"+$('#awd-adm-lv2').val()+"'></td>"+
                                "<td adm-id='"+$('#awd-adm-lv3').val()+"'></td>"+
                                "<td><a type='button' class='btn btn-xs btn-danger adm-delete'>删除</a></td>"+
                                "</tr>";
                        }
                    }
                }else{
                    id=$('#awd-adm-lv2').val();
                    name=$('#awd-adm-lv2 option:selected').text(); 
                    //当前区域是否已在列表中
                    bExists=false;
                    $("#adms-modal tbody tr").each(function(rowIndex) {
                        if($(this).attr('adm_id')==id){
                            bExists=true;  
                            //跳出each循环
                            return false;
                        };
                    });
                    if(bExists){
                        toastr.error(
                            name+"已经在列表中！",
                            "操作错误：",
                            {timeOut: 800, positionClass: "toast-center-center"}
                        );         
                     return;                    
                    }else{
                        s="<tr adm-id="+id+" adm-name='"+name+"'>"+
                            "<td adm-id='"+$('#awd-adm-lv1').val()+"'>"+$('#awd-adm-lv1 option:selected').text()+"</td>"+
                            "<td adm-id='"+$('#awd-adm-lv2').val()+"'>"+$('#awd-adm-lv2 option:selected').text()+"</td>"+   
                            "<td adm-id='"+$('#awd-adm-lv3').val()+"'></td>"+
                            "<td><a type='button' class='btn btn-xs btn-danger adm-delete'>删除</a></td>"+
                            "</tr>";
                    }
                }                
            }else{
                id=$('#awd-adm-lv3').val();
                name=$('#awd-adm-lv3 option:selected').text();
                //当前区域是否已在列表中
                bExists=false;
                $("#adms-modal tbody tr").each(function(rowIndex) {
                    if($(this).attr('adm_id')==id){
                        bExists=true;  
                        //跳出each循环
                        return false;
                    };
                });
                if(bExists){
                    toastr.error(
                        name+"已经在列表中！",
                        "操作错误：",
                        {timeOut: 800, positionClass: "toast-center-center"}
                    );         
                    return;                    
                }else{
                    s="<tr adm-id="+id+" adm-name='"+name+"'>"+
                        "<td adm-id='"+$('#awd-adm-lv1').val()+"'>"+$('#awd-adm-lv1 option:selected').text()+"</td>"+
                        "<td adm-id='"+$('#awd-adm-lv2').val()+"'>"+$('#awd-adm-lv2 option:selected').text()+"</td>"+
                        "<td adm-id='"+$('#awd-adm-lv3').val()+"'>"+$('#awd-adm-lv3 option:selected').text()+"</td>"+
                        "<td><a type='button' class='btn btn-xs btn-danger adm-delete'>删除</a></td>"+
                        "</tr>";
                }
            };
            $('#adms-modal tbody').append(s);
        });        
        $('#adms-modal tbody').on('click', 'a.adm-delete', function(){        
            $(this).closest('tr').remove();
        });
        $('#adms-modal .btn-confirm').click(function(){             
            var aAdm=[],aT=[];
            $("#adms-modal tbody tr").each(function(rowIndex) {   
                aAdm.push({
                    'id':$(this).attr('adm-id'),
                    'name':$(this).attr('adm-name'),
                    'lvs':{
                        "lv1":{
                            "id":$(this).find("td:nth-child(1)").attr('adm-id'),
                            "name":$(this).find("td:nth-child(1)").text(),
                        },
                        "lv2":{
                            "id":$(this).find("td:nth-child(2)").attr('adm-id'),
                            "name":$(this).find("td:nth-child(2)").text(),
                        },
                        "lv3":{
                            "id":$(this).find("td:nth-child(3)").attr('adm-id'),
                            "name":$(this).find("td:nth-child(3)").text(),
                        },
                    }
                });
                aT.push($(this).attr('adm-name'));                
            });    
            if( aAdm.length==0){
                toastr.error(
                    "奖项限定区域不能为空！",
                    "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );                  
            }else{                
                var el_id=$('#el-id').val();
                var td=$('#'+el_id).closest('td');
                $(td).find("span").text(aT.join(","));   
                $("#"+el_id).val(JSON.stringify(aAdm));                              
                $('#adms-modal').modal('hide'); 
            };
        });     
        $('#adms-modal .btn-clearall').click(function(){
            var el_id=$('#el-id').val();
            var td=$('#'+el_id).closest('td');   
            $(td).find("span").text("无");
            $("#"+el_id).val('[]'); 
            $('#adms-modal').modal('hide');   
        });







        







        



        

        {% if not can_edit %}
            $('#data-content input,#data-content .btn,#data-content select').attr("disabled",true);
        {% endif %}
        

        {% if form.instance.company %}
            $('#co').val('{{form.instance.company.id}}');
            $('#id_activityawards_activity-__prefix__-company').val('{{form.instance.company}}');   
        {% else %}
            $('#co').val('');
            $('#product_label,#agent_label,#award_label,#alter_label').attr("disabled","disabled"); 
        {% endif %}

        $('#co').change(function(){     
            var v=$('#co').val();            
            $('#id_company').val(v);
            if(v==''){
                $('#product_label,#agent_label,#award_label,#alter_label').attr("disabled",true);               
            }else{
                $('#product_label,#agent_label,#award_label,#alter_label').attr("disabled",false);
            }     
        });
      

        {% if form.instance.id %}
            $('#co').val('{{form.instance.company_id}}'); 
        {% endif %}


        $.datetimepicker.setLocale('zh');

        $('.datetimepicker').datetimepicker({
            i18n:{
                zh:{
                    months:['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月',],
                    dayOfWeek:["一", "二", "三", "四","五", "六", "日",]
                }
            },
            //timepicker:true,
            format:'Y-m-d H:i:s',        
        });
        
        $('#product_label').autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: '/obj/ajax/autocomplete/product/',
                    dataType: "json",
                    data: {
                        term:   $("#product_label").val() ,//搜索栏里的内容
                        company_id:  $('#id_company').val() ,//额外参数
                    },
                    success: function(data) {
                        response(data);
                    }
                });
            },
            select: function (event, ui) {
                $("#product_id").val(ui.item.value);
                $("#product_label").val(ui.item.label);
                return false;
            }
        });

        $('#agent_label').autocomplete({   
            source: function(request, response) {
                $.ajax({
                    url: '/obj/ajax/autocomplete/agent/',
                    dataType: "json",
                    data: {
                        term:   $("#agent_label").val() ,//搜索栏里的内容
                        company_id:  $('#id_company').val() ,//额外参数
                    },
                    success: function(data) {
                        response(data);
                    }
                });
            },            
            select: function (event, ui) {
                $("#agent_id").val(ui.item.value);
                $("#agent_label").val(ui.item.label);
                return false;
            }
        });
        $('#level_label').autocomplete({            
            source: '/obj/ajax/autocomplete/level/',            
            select: function (event, ui) {
                $("#level_id").val(ui.item.value);
                $("#level_label").val(ui.item.label);
                return false;
            }
        });

        $('#award_label').autocomplete({ 
            source: function(request, response) {
                $.ajax({
                    url: '/obj/ajax/autocomplete/award/',
                    dataType: "json",
                    data: {
                        term:   $("#award_label").val() ,//搜索栏里的内容
                        company_id:  $('#id_company').val() ,//额外参数
                    },
                    success: function(data) {
                        response(data);
                    }
                });
            },  
            select: function (event, ui) {
                $("#award_id").val(ui.item.value);
                $("#award_label").val(ui.item.label);
                return false;
            }
        });
        $('#alter_label').autocomplete({      
            source: function(request, response) {
                $.ajax({
                    url: '/obj/ajax/autocomplete/award/',
                    dataType: "json",
                    data: {
                        term:   $("#alter_label").val() ,//搜索栏里的内容
                        company_id:  $('#id_company').val() ,//额外参数
                    },
                    success: function(data) {
                        response(data);
                    }
                });
            },            
            select: function (event, ui) {
                $("#alter_id").val(ui.item.value);
                $("#alter_label").val(ui.item.label);
                return false;
            }
        });


        //2021-01-20
        /* 2022-12-22
        $('.add-batch').click(function(){
            var id=$('#batch_id').val();
            var label=$('#batch_label').val();
            if(id==''){
                toastr.error("请先选择营销层级！", "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;
            }else{
                var e=false;
                $("#sel-batch option").each(function(){
                    if($(this).val() == id){
                        e=true;
                        return false;          
                    }
                });
                if(e){
                    toastr.error(label+"已在列表中！", "操作错误：",
                        {timeOut: 800, positionClass: "toast-center-center"}
                    );
                    return;
                }else{
                    $('#sel-batch').append("<option value='"+id+"'>"+label+"</option>");
                }
            };
        });
        */









        $('.add-product').click(function(){
            var id=$('#product_id').val();
            var label=$('#product_label').val();
            if(id==''){
                toastr.error("请先选择产品！", "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;
            }else{
                var e=false;
                $("#sel-product option").each(function(){
                    if($(this).val() == id){
                        e=true;
                        return false;          
                    }
                });
                if(e){
                    toastr.error(label+"已在列表中！", "操作错误：",
                        {timeOut: 800, positionClass: "toast-center-center"}
                    );
                    return;
                }else{
                    $('#sel-product').append("<option value='"+id+"'>"+label+"</option>");
                }
            };
        });
        $('.add-agent').click(function(){
            var id=$('#agent_id').val();
            var label=$('#agent_label').val();
            if(id==''){
                toastr.error("请先选择经销商！", "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;
            }else{
                var e=false;
                $("#sel-agent option").each(function(){
                    if($(this).val() == id){
                        e=true;
                        return false;          
                    }
                });
                if(e){
                    toastr.error(label+"已在列表中！", "操作错误：",
                        {timeOut: 800, positionClass: "toast-center-center"}
                    );
                    return;
                }else{
                    $('#sel-agent').append("<option value='"+id+"'>"+label+"</option>");
                }
            };
        });
        $('.add-level').click(function(){
            var id=$('#level_id').val();
            var label=$('#level_label').val();
            if(id==''){
                toastr.error("请先选择营销层级！", "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;
            }else{
                var e=false;
                $("#sel-level option").each(function(){
                    if($(this).val() == id){
                        e=true;
                        return false;          
                    }
                });
                if(e){
                    toastr.error(label+"已在列表中！", "操作错误：",
                        {timeOut: 800, positionClass: "toast-center-center"}
                    );
                    return;
                }else{
                    $('#sel-level').append("<option value='"+id+"'>"+label+"</option>");
                }
            };
        });

        $('.add-adm').click(function(){            
            var id="";;
            var label="";
            if($('#city').val()!=''){
                if($('#province').val()==''){
                    toastr.error("选择了市级区域，省级区域不能为空！", "操作错误：",
                        {timeOut: 800, positionClass: "toast-center-center"}
                    );
                    
                    return false;
                };
                id=$('#city').val();
                label=$('#province').find("option:selected").text()+$('#city').find("option:selected").text();
            }else{
                if($('#province').val()!=''){
                    id=$('#province').val();
                    label=$("#province").find("option:selected").text();
                }            
            }
            if(id==''){
                toastr.error("请先选择扫码区域！", "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;
            }else{
                var e=false;
                $("#sel-adm option").each(function(){
                    if($(this).val() == id){
                        e=true;
                        return false;          
                    }
                });
                if(e){
                    toastr.error(label+"已在列表中！", "操作错误：",
                        {timeOut: 800, positionClass: "toast-center-center"}
                    );
                    return;
                }else{
                    $('#sel-adm').append("<option value='"+id+"'>"+label+"</option>");
                }
            };
        });


        $('.add-award').click(function(){     
            {% if not can_edit %}
                return;
            {% endif %}

            //2020-07-30 添加前数据检查
            if ($('#id_scheme').val()==3){
                if( $.isEmpty($('#award_id').val()) 
                    || $.isEmpty($('#award_name').val())
                    || $.isEmpty($('#award_name').val())
                ){
                    toastr.error("奖项名称，对应奖品不能为空", "操作错误：",
                        {timeOut: 2000, positionClass: "toast-center-center"}
                    );
                    return;
                }
            }else{
                if( $.isEmpty($('#award_id').val()) 
                    || $.isEmpty($('#award_name').val())
                    || $.isEmpty($('#award_name').val())
                    || $.isEmpty($('#rate').val())
                ){
                    toastr.error("奖项名称，对应奖品, 抽奖概率不能为空", "操作错误：",
                        {timeOut: 2000, positionClass: "toast-center-center"}
                    );
                    return;
                }                
            };
            

            var prefix='#id_activityawards_activity-';  
            $(prefix+'__prefix__-name').val($('#award_name').val());                
            $(prefix+'__prefix__-award').val($('#award_id').val());
            $(prefix+'__prefix__-alternative').val($('#alter_id').val());  
            $(prefix+'__prefix__ .award_name').text($('#award_name').val());
            $(prefix+'__prefix__ .award').text($('#award_label').val());
            $(prefix+'__prefix__ .alternative').text($('#alter_label').val());           

            $(prefix+'__prefix__ .needcheck').text($('#needcheck').find("option:selected").text()); 
            var count = $('#tb_award tbody tr').length; 
            var tmplMarkup = '<tr class="p">'+$(prefix+'__prefix__').html()+'</tr>';    
            var compiledTmpl = tmplMarkup.replace(/__prefix__/g, count);     
            $('#tb_award tbody').append(compiledTmpl);   

            //添加后的设置INPUT值            
            $(prefix+count+'-qty_upper').val($('#qty_upper').val());  
            $(prefix+count+'-qty_input').val($('#qty_input').val()); 
            $(prefix+count+'-qty_daily').val($('#qty_daily').val()); 
            $(prefix+count+'-rate').val($('#rate').val()); 

            $(prefix+'TOTAL_FORMS').attr('value', (count+1));   
        });


        $('.select2_multiple').on('click','option',function(){
            $(this).remove();
        });


        $('.btn-save').click(function(){
            {% if not can_edit %}
                return;
            {% endif %}
            
            var a=[];
            $("#sel-product option").each(function (){
                a.push($(this).val());
            });  
            if(a.length>0){
                $('#id_products').val(a.join(','));
            }else{
                $('#id_products').val('');
            };

            a=[];
            $("#sel-agent option").each(function (){
                a.push($(this).val());
            });  
            if(a.length>0){
                $('#id_agents').val(a.join(','));
            }else{
                $('#id_agents').val('');
            };

            a=[];
            $("#sel-level option").each(function (){
                a.push($(this).val());
            });  
            if(a.length>0){
                $('#id_agent_lvs').val(a.join(','));
            }else{
                $('#id_agent_lvs').val('');
            };

            a=[];
            $("#sel-adm option").each(function (){
                a.push($(this).val());
            });  
            if(a.length>0){
                $('#id_adm_ids').val(a.join(','));
            }else{
                $('#id_adm_ids').val('');
            };

            //2021-01-20
            a=[];
            $("#sel-batch option").each(function (){
                a.push($(this).val());
            });            
            if(a.length>0){
                $('#id_batch_ids').val(a.join(','));
            }else{
                $('#id_batch_ids').val('');
            };


            
            $.SubmitForm('#obj_form form','{{request.path}}');
        });      

        
        $("#province").change(function() {
            var province_id = $(this).val();
            getCity(province_id,$('#city'));
        });     

        function getCity(province_id,sel) {
            var me=sel;
            $.ajax({

                url: "/gis/adm/2/"+province_id+"/",
                //2023-01-03
                url: "/utils/adm/ajax/2/?parent_id="+province_id,

                success: function(data) {
                    $(me).empty();
                    $('#area').empty();
                    data=data.result;
                    $.each(data,function(idx){$(me).append("<option value='"+data[idx].id+"'>"+data[idx].name+"</option>")});
                    $(me).append("<option value='' selected='selected'>---------</option>");
                },
                dataType: 'json',                
            });
        };
        function getCounty(city_id,sel) {
            var me=sel;
            $.ajax({
            
                url: "/gis/adm/3/"+city_id+"/",
                // 2023-01-03
                url: "/utils/adm/ajax/3/?parent_id="+city_id,

                success: function(data) {
                    data=data.result;
                    $(me).empty();
                    $.each(data,function(idx){$(me).append("<option value='"+data[idx].id+"'>"+data[idx].name+"</option>")});
                    $(me).append("<option value='' selected='selected'>---------</option>");
                },
                dataType: 'json',
                //jsonp: 'callback'
            });
        };



      


    {% endblock %}


    {% block subtitle-1 %}
        {% trans "营销活动" %}
    {% endblock %}
    {% block subtitle-2 %}
        {% trans "活动设置" %}
    {% endblock %}

    <span style="margin-left:10px; color:green; ">
        {% block subtitle-3 %}
            {% if form.instance.id %}
                {% trans "修改" %}
            {% else %}
                {% trans "新建" %}
            {% endif %}
        {% endblock %}

    </span>



{% block form_content %}
    {{ block.super }}  
    



    <div class="form-group ">
        <label class="col-sm-1 control-label ">{% get_verbose_field_name form.instance 'company' %} </label>
        <div class="col-sm-5">
            <select id='co'>
                {% for co in companys %}
                    <option value='{{co.0}}'>{{co.1}}</option>
                {% endfor %}
                <option value=''>------------------------------</option>
            </select>        
        </div>
        
        <label class="col-sm-1 control-label ">{% get_verbose_field_name form.instance 'name' %} </label>
        <div class="col-sm-5">{{ form.name }}</div>
        <!--
        <label class="col-sm-1 control-label ">{% get_verbose_field_name form.instance 'digest' %} </label>
        <div class="col-sm-5">{{ form.digest }}</div>
        -->
        

    </div>
   
    <div class="form-group ">
        <label class="col-sm-1 control-label ">{% get_verbose_field_name form.instance 'target' %} </label>
        <div class="col-sm-2">{{ form.target }}</div>
         <label class="col-sm-1 control-label ">{% get_verbose_field_name form.instance 'lblpkg_id' %} </label>
        <div class="col-sm-2">{{ form.lblpkg_id }}</div>
        <label class="col-sm-1 control-label ">{% get_verbose_field_name form.instance 'distribution' %} </label>
        <div class="col-sm-2">{{ form.distribution }}</div>
        <label class="col-sm-1 control-label ">{% get_verbose_field_name form.instance 'priority' %} </label>
        <div class="col-sm-2">{{ form.priority }}</div>
    </div>
    <div class="form-group ">
        <label class="col-sm-1 control-label ">{% get_verbose_field_name form.instance 'wx_account' %} </label>
        <div class="col-sm-2">{{ form.wx_account }}</div>
        <label class="col-sm-1 control-label ">{% get_verbose_field_name form.instance 'scheme' %} </label>
        <div class="col-sm-2">{{ form.scheme }}</div>
        <label class="col-sm-1 control-label ">{% get_verbose_field_name form.instance 'template' %} </label>
        <div class="col-sm-2">{{ form.template }}</div>
        <label class="col-sm-1 control-label ">{% get_verbose_field_name form.instance 'background' %} </label>
        <div class="col-sm-2">{{ form.background }}</div>
    </div>
    <div class="form-group ">
        <label class="col-sm-1 control-label">{% get_verbose_field_name form.instance 'products' %}</label>
        <div class='col-sm-2'>
            <div class="input-group">
                <input type="text" class="form-control" id="product_label" placeholder="所有产品">
                <input type="hidden" id="product_id" />
                <span class="input-group-btn"><button type="button" class="btn btn-success add-product">
                <span class='glyphicon glyphicon-arrow-down'></span></button></span>
            </div>        
        </div>  

        <label class="col-sm-1 control-label">{% get_verbose_field_name form.instance 'agents' %}</label>
        <div class='col-sm-2'>
            <div class="input-group">            
                <input  class=' form-control' id="agent_label" placeholder='所有经销商'/>
                <input type="hidden" id="agent_id" />
                <span class="input-group-btn"><button type="button" class="btn btn-success add-agent">
                    <span class='glyphicon glyphicon-arrow-down'></span></button></span>
            </div>
        </div> 

        <label class="col-sm-1 control-label">{% get_verbose_field_name form.instance 'agent_lvs' %}</label>
        <div class='col-sm-2'>
            <div class="input-group"> 
                <input  class=' form-control' id="level_label" placeholder='所有层级'/>
                <input type="hidden" id="level_id" />
                <span class="input-group-btn"><button type="button" class="btn btn-success add-level">
                    <span class='glyphicon glyphicon-arrow-down'></span></button></span>
            </div>        
        </div> 

        <label class="col-md-1 control-label">{% get_verbose_field_name form.instance 'adm_ids' %}</label>  
        <div class='col-md-1'>
            <select id="province" class="form-control adm"></select>
        </div>
        <div class='col-md-1'>    
            <div class="input-group"> 
                <select id="city" class="form-control adm">
                    <option value="" selected="selected">---------</option>                
                </select>
                <span class="input-group-btn"><button type="button" class="btn btn-success add-adm">
                    <span class='glyphicon glyphicon-arrow-down'></span></button></span>
            </div>
        </div>   
    </div>

    <div class="form-group" style='margin-top:-28px;'>
        <div class='col-sm-2 col-md-offset-1'>
            <select class="select2_multiple form-control" id="sel-product" multiple="multiple">
                {% for o in products %}
                    <option value='{{o.0}}'>{{o.1}}</option>
                {% endfor %}                                     
            </select>        
        </div>
        <div class='col-sm-2 col-md-offset-1'>
            <select class="select2_multiple form-control" id='sel-agent' multiple="multiple">
                {% for o in agents %}
                    <option value='{{o.0}}'>{{o.1}}</option>
                {% endfor %}   
                                  
            </select>        
        </div>
        <div class='col-sm-2 col-md-offset-1'>
            <select class="select2_multiple form-control" id="sel-level" multiple="multiple">
                {% for o in levels %}
                    <option value='{{o.0}}'>{{o.1}}</option>
                {% endfor %}                       
            </select>        
        </div>
        <div class='col-sm-2 col-md-offset-1'>
            <select class="select2_multiple form-control" id="sel-adm" multiple="multiple">
                {% for o in adms %}
                    <option value='{{o.0}}'>{{o.1}}</option>
                {% endfor %}        
            </select>        
        </div>
    </div>    









     <div class="form-group ">
        <label class="col-sm-1 control-label">{% get_verbose_field_name form.instance 'tm_start' %}</label>
        <div class='col-sm-2'> {{ form.tm_start }}</div>
        <label class="col-sm-1 control-label">{% get_verbose_field_name form.instance 'tm_end' %}</label>
        <div class='col-sm-2'> {{ form.tm_end }}</div>
        <label class="col-sm-1 control-label">{% get_verbose_field_name form.instance 'status' %}</label>
        <div class='col-sm-2'> {{ form.status }}</div>
        <label class="col-sm-1 control-label">{% get_verbose_field_name form.instance 'digest' %}</label>
        <div class='col-sm-2'> {{ form.digest }}</div>

    </div>
	
     <div class="form-group ">
        <label class="col-sm-1 control-label">{% get_verbose_field_name form.instance 'fhtm_start' %}</label>
        <div class='col-sm-2'> {{ form.fhtm_start }}</div>
        <label class="col-sm-1 control-label">{% get_verbose_field_name form.instance 'fhtm_end' %}</label>
        <div class='col-sm-2'> {{ form.fhtm_end }}</div>


        <label class="col-sm-1 control-label">特殊时段</label>
        <div class='col-sm-5' style='padding-top:8px;'> 
            <span id='timebucket-cfg' style='color:green;'></span>
            <a class='btn-show-timebucket' style='cursor:pointer;'>设置</a>
            <a class="btn btn-primary btn-save" type="button" style="float:right;">
                {% trans '保存' %}
            </a>
        </div>

    </div>
    <div class="form-group ">
        <label class="col-md-1 control-label">指定发货批次</label>  
        <div class='col-md-11'>
            <select class="form-control js-example-basic-multiple" id='sel-delivery_batches' multiple="multiple"></select> 
        </div>       
    </div>
	

    <!--dlg-timebucket -->
    <div class="modal fade bs-example-modal-lg" id='timebucket-modal' tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span></button>
                    <h4 class="modal-title">特殊时段设置：</h4>
                </div>
                <div class="modal-body"> 
                    <div class='form-group' >
                        <label class='col-sm-1 control-label'>时间段名</label>
                        <div class='col-sm-11'><input id='timebucket-name' /></div>        
                    </div>
                    <div class='clearfix' style='margin-bottom:8px;'></div>
                    <div class='form-group'>
                        <label class='col-sm-1 control-label'>开始时间</label>
                        <div class='col-sm-2'>
                            <input id='interval-start' class='form-control' />
                        </div>
                        <label class='col-sm-1 control-label'>结束时间</label>
                        <div class='col-sm-2'>
                            <input id='interval-end' class='form-control' />
                        </div>
                        <span>
                            <a type="button" class='btn btn-success add-interval'>
                                <span class='glyphicon glyphicon-arrow-down' style='padding-right:5px;'></span>添加
                        </a></span>  
                        <a type="button" class='pull-right btn btn-danger btn-clearall'>清除设置</a>
                    </div>
                    <div class="table-responsive">
                        <table id='tb-timebucket' class='table table-bordered table-condensed table-hover'>
                            <thead>
                                <th>开始时间</th>
                                <th>结束时间</th>                                
                                <th>操作</th>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <a type="button" class="btn btn-primary btn-confirm" >保存</a>
                    <a type="button" class="btn btn-default btn-cancel" data-dismiss="modal">取消</a>    
                </div>
            </div>
        </div>
    </div>
    <!--dlg-adms -->
    <div class="modal fade bs-example-modal-lg" id='adms-modal' tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span></button>
                    <h4 class="modal-title">奖项区域设置：</h4>
                </div>
                <div class="modal-body"> 
                    <input type='hidden' id='el-id' />
                    <div class="form-group ">
                        <label class="col-md-1 control-label ">{% trans '省份:' %}</label>  
                        <div class='col-md-2'>
                            <select class='form-control' id='awd-adm-lv1' />                            
                        </div>
                        <label class="col-md-1 control-label">{% trans '城市:' %}</label>  
                        <div class='col-md-2'>    
                            <select class='form-control' id='awd-adm-lv2' />                            
                        </div>   
                        <label class="col-md-1 control-label">{% trans '区县:' %}</label>  
                        <div class='col-md-2'>  
                            <select class='form-control' id='awd-adm-lv3' />                            
                        </div>
                        <div class='col-sm-1'>
                            <div class="input-group">                                                 
                                <span class="input-group-btn"><button type="button" class="btn btn-success dlg-add-adm">
                                    <span class='glyphicon glyphicon-arrow-down'></span>添加</button></span>
                            </div>
                        </div>
                        <a type="button" class='pull-right btn btn-danger btn-clearall'>清除设置</a>

                    </div>

                    <div class="table-responsive">
                        <table class='table table-bordered table-condensed table-hover'>
                            <thead>
                                <th>省份</th>
                                <th>城市</th>
                                <th>区县</th>
                                <th>操作</th>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <a type="button" class="btn btn-primary btn-confirm" >保存</a>
                    <a type="button" class="btn btn-default btn-cancel" data-dismiss="modal">取消</a>    
                </div>
            </div>
        </div>
    </div>
    


{% endblock %}





{% block fmset %}    
        
        <div class='col-md-1' style='padding-left:0px;'>            
            <input type="text" id='award_name' class="form-control" placeholder="{% trans '奖项名称' %}">
        </div>

        <div class='col-md-2'>
            <input type='hidden' id='award_id' />
            <input type="text" id='award_label' class="form-control"  placeholder="{% trans '奖品' %}">
        </div>
        <div class='col-md-2'>
            <input type='hidden' id='alter_id'/>
            <input id="alter_label" type="text" class="form-control"  placeholder="{% trans '超限后替代品' %}">
        </div>
        <div class='col-md-1'><select  class="form-control" id='needcheck' >
                <option value='False'>{% trans '不需审核' %}</option>
                <option value='True'>{% trans '需要审核'%}</option>
            </select>
        </div>

        <div class='col-md-1'><input type="text" class="form-control" id='rate' placeholder="{% trans '中奖概率' %}"></div>
        <div class='col-md-1'><input type="text" class="form-control" id='timebucket_rate' placeholder="{% trans '时段中奖率' %}"></div>

        
        <div class='col-md-1'><input type="text" class="form-control" id='qty_upper' placeholder="{% trans '上限数量' %}"></div>
        <div class='col-md-1'><input type="text" class="form-control" id='qty_input' placeholder="{% trans '投放数量' %}"></div> 
        <div class='col-md-1'><input type="text" class="form-control" id='qty_daily' placeholder="{% trans '每日上限' %}"></div> 

        <table style="display:none;">
            <tr id="id_activityawards_activity-__prefix__" >                
                {{formset.empty_form.id}}{{formset.empty_form.activity}}{{formset.empty_form.name}}
                {{formset.empty_form.award}}{{formset.empty_form.alternative}}               
                <td>{{ formset.empty_form.DELETE }}</td>               
                <td><span class='award_name'></span></td> 
                <td><span class='award'></span></td> 
                <td><span class='alternative'></span></td>    
                <td>{{formset.empty_form.needcheck}}</td>  
                <td>{{formset.empty_form.rate}}</td> 
                <td>{{formset.empty_form.timebucket_rate}}</td>
                <td>{{formset.empty_form.qty_upper}}</td>
                <td>{{formset.empty_form.qty_input}}</td> 
                <td>{{formset.empty_form.qty_daily}}</td>
                <td class='awd-adms'>                     
                    {{formset.empty_form.adms}}<span>无</span>                       
                    <a class="btn btn-default btn-xs btn-adms-cfg" >设置</a>
                </td>

            </tr>
        </table>

        <div class='pull-right'>
            <span><a type="button" class='btn btn-success add-award'>
                <span class='glyphicon glyphicon-arrow-down'></span>添加
            </a></span>
        </div>
        
    <div class='clearfix'/>
    
    <div class='table-responsive'>
        <table id='tb_award' class="table table-condensed table-bordered table-hover">
            <thead><tr>
                <th>{% trans '删除' %}</th>
                <th>{% trans '奖项名称 ' %}</th>
                <th>{% trans '奖品 ' %}</th>
                <th>{% trans '超限后替代品' %}</th>
                <th>{% trans '中奖审核' %}</th>
                <th>{% trans '中奖概率' %}</th>
                <th>{% trans '时段中奖率' %}</th>
                <th>{% trans '上限数量' %}</th>
                <th>{% trans '投放数量' %}</th> 
                <th>{% trans '每日上限' %}</th> 
                <th>{% trans '奖项区域限定' %}</th>                 
            </tr></thead>
            <tbody>
                {% for f in formset %}
                <tr  class='p'>
                    {{f.id}}{{f.activity}}{{f.name}}{{f.award}}{{f.alternative}}                    
                    <td>{{f.DELETE}}</td>      
                    <td>{{ f.instance.name }}</td>
                    <td>{{ f.instance.award.name }}</td>
                    <td>{{ f.instance.alternative.name}}</td>    
                    <td>{{ f.needcheck }}</td>
                    <td>{{ f.rate }}</td>
                    <td>{{ f.timebucket_rate }}</td>
                    <td>{{ f.qty_upper }}</td>
                    <td>{{ f.qty_input }}</td>   
                    <td>{{ f.qty_daily }}</td>  
					<td class='awd-adms'>                     
                        {{f.adms}}<span style='color:green;'></span>                       
                        <a class="btn btn-default btn-xs btn-adms-cfg" >设置</a>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
            {{ formset.management_form }}                
        </table>
    </div>

	 
	
    
{% endblock %}
