{% extends 'obj_form.html' %}
{% load i18n %}
{% load tj_filters %}
  
    <style>     
      

    </style>

    {% block js %}
        {{ block.super }}
        
        /*
        $('#div_label,#subdiv_label,.add-div,.add-subdiv').attr("disabled",true);
        */

        {% ifnotequal user.company.level_id 1%}
            {% if not user.perms.company.sys_admin%}
                $('#data-content input,#data-content .btn,#data-content select').attr("disabled",true);
            {% endif %}
        {% endifnotequal %}
        

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

        $('#co').change(function(){
            $('#id_company').val($(this).val());
            var b;
            if($('#co').val()==''){
                b=true;
            }else{
                b=false;
            }
            $('#product_label,#agent_label,#div_label,#subdiv_label').attr("disabled",b)
        });
      


       

        $('.datepicker').datepicker({dateFormat: 'yy-mm-dd'});
        //$('.datepicker').datepicker('setDate',new Date());
        setDatePickerZh();



        $.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:  $('#co').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:  $('#co').val() ,//额外参数
                    },
                    success: function(data) {
                        response(data);
                    }
                });
            },            
            select: function (event, ui) {
                $("#agent_id").val(ui.item.value);
                $("#agent_label").val(ui.item.label);
                return false;
            }
        });
        $('#div_label').autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: '/obj/ajax/autocomplete/saldiv/',
                    dataType: "json",
                    data: {
                        term:   $("#div_label").val() ,//搜索栏里的内容
                        company_id:  $('#co').val() ,//额外参数
                    },
                    success: function(data) {
                        response(data);
                    }
                });
            },
            select: function (event, ui) {
                $("#div_id").val(ui.item.value);
                $("#div_label").val(ui.item.label);
                
                //2020-10-19
                get_subdivs(ui.item.value);    
                return false;
            }
        });

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

        $('#div_id').change(function(){
            var saldiv_id=$(this).val();           
            
            if (saldiv_id==''){
                $('#subdiv_id').empty();
                $('#subdiv_id').append('<option value="">所有片区</option>')
            }else{
                get_subdivs($(this).val());
            }
        });

        function get_subdivs(saldiv_id){
            var me=$('#subdiv_id');
            $.ajax({
                url: "/obj/ajax/subsaldiv/"+saldiv_id+"/",
                success: function(data) {
                    $(me).empty();
                    $.each(data,function(i,d){$(me).append("<option value='"+d[0]+"'>"+d[1]+"</option>")});                   
                },
                dataType: 'json'               
            });  
        };


        $('.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-div').click(function(){
            var id=$('#div_id').val();
            {% ifequal user.id 1 %}
                var label=$('#div_label').val();
            {% else %}
                var label=$('#div_id').find("option:selected").text();
            {% endifequal %}            
            if(id==''){
                toastr.error("请先选择战区！", "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;
            }else{
                var e=false;
                $("#sel-div 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-div').append("<option value='"+id+"'>"+label+"</option>");
                }
            };
        });

        $('.add-subdiv').click(function(){
            var id=$('#subdiv_id').val();
            {% ifequal user.id 1 %}
                var label=$('#subdiv_label').val();
            {% else %}
                var label=$('#subdiv_id').find("option:selected").text();
            {% endifequal %}
            if(id==''){
                toastr.error("请先选择分区！", "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;
            }else{
                var e=false;
                $("#sel-subdiv 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-subdiv').append("<option value='"+id+"'>"+label+"</option>");
                }
            };
        });


        $('.add-rebate').click(function(){           

            var prefix='#id_channelrebate_promotion-';
            var count = $('#formset').find('.rebate').length;
            var tmplMarkup = $('#empty-form').html();
            var compiledTmpl = tmplMarkup.replace(/__prefix__/g, count);     
            $('#formset').append(compiledTmpl);
            $(prefix+'TOTAL_FORMS').attr('value', (count+1));   
        });        
        

        $('#obj_form').on('click','.add-pval',function(){
            var div=$(this).closest('.rebate');
            var sel=$(div).find('.sel-plv');
            var id=sel.val();
            var label=sel.find("option:selected").text();
            var e=false;
            var val=$(div).find('.pval').val();

           

            if($.isEmpty(id)){
                toastr.error("营销层级不能为空", "操作错误：",
                   {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;
            };

            if(val==''){
                toastr.error("未输入层级返利金额", "操作错误：",
                   {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;
            };
            $(div).find(".sel-plvs option").each(function(){
                if($(this).val() == id){
                    e=true;
                    return false;
                }
            });
            if(e){
                toastr.error(label+"已在列表中！", "操作错误：",
                   {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;
            }else{
                $(div).find('.sel-plvs').append("<option value='"+id+"' o-vl='"+val+"' o-nm='"+label+"' o-rc='"+
                $(sel).find("option:selected").attr("o-rec")+"'>"+label+":"+val+"</option>");
            };

            //2020-11-03
            $('#formset .select2_multiple').on('dblclick','option',function(){
                $(this).remove();
            });

        });

        $('#obj_form').on('change','.sel-lv',function(){
            var me=$(this);
            $.ajax({
                url: '/company/ajax/parent/level/'+$(this).val()+'/',
                dataType: "json",
                success: function(data) {
                    var div=$(me).closest('.rebate');
                    var html='';
                    var lv,b;
                    for(i in data.parents){
                        lv=data.parents[i];
                        html=html+"<option value='"+lv.id+"' o-rec='"+lv.rec+"'>"+lv.name+"</option>";
                    };
                    $(div).find('.sel-plv').html(html);
                    if(html==''){
                        b=true;
                    }else{
                        b=false
                    }
                    $(div).find('.add-pval').attr('disabled',b);
                }
            });
        });

        $('.btn-save').click(function(){           
           
            if($.isEmpty($('#id_company').val()) || $.isEmpty($('#id_tm_start').val()) || $.isEmpty($('#id_tm_end').val()) || $.isEmpty($('#id_name').val())){
                toastr.error("公司名称,活动名称,开始时间,结束时间 不能为空", "操作错误：",
                        {timeOut: 1800, positionClass: "toast-center-center"}
                );
                return;
            };

            var a=[];
            var s='';
            $("#formset .rebate").each(function (){
                a=[];
                var me=$(this);
                $(me).find('.sel-plvs option').each(function(){
                    s=$(this).val()+'|'+$(this).attr('o-rc')+'|'+$(this).attr('o-vl')+'|'+$(this).attr('o-nm');
                    a.push(s);
                });
                if(a.length>0){
                    $(me).find('.pvals').val(a.join('&'));
                };
            });
            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-div option").each(function (){
                a.push($(this).val());
            });  
            if(a.length>0){
                $('#id_div_ids').val(a.join(','));
            }else{
                $('#id_div_ids').val('');
            };
            a=[];
            $("#sel-subdiv option").each(function (){
                a.push($(this).val());
            });  
            if(a.length>0){
                $('#id_subdiv_ids').val(a.join(','));
            }else{
                $('#id_subdiv_ids').val('');
            };
            $.SubmitForm('#obj_form form','{{request.path}}');
        });

        {% for f in formset %}
            var prefix='#id_channelrebate_promotion-';
            var count = $('#formset').find('.rebate').length;
            var tmplMarkup = $('#empty-form').html();
            var compiledTmpl = tmplMarkup.replace(/__prefix__/g, count);
            $('#formset').append(compiledTmpl);
            $(prefix+count+'-id').val('{{f.instance.id}}');
            $(prefix+count+'-level').val('{{f.instance.level.id}}');
            $(prefix+count+'-vtype_id').val('{{f.instance.vtype_id}}');
            $(prefix+count+'-val').val('{{f.instance.val}}');
            $(prefix+count+'-distance').val('{{f.instance.distance}}');
            if("{{f.instance.pvals|default_if_none:''}}".length>0){
                var html='';
                var aa='{{f.instance.pvals}}'.split('&');
                for(i=0;i<aa.length;i++){
                    a=aa[0].split('|');
                    html=html+"<option value='"+a[0]+"' o-rc='"+a[1]+"' o-vl='"+a[2]+"' o-nm='"+a[3]+"'>"+a[3]+':'+a[2]+"</option>";
                };
                $(prefix+count).find('.sel-plvs').html(html);
            };
            $(prefix+'TOTAL_FORMS').attr('value', (count+1));
        {% endfor %}
        //2020-11-06
        $('#data-content [data-toggle="tooltip"]').tooltip();

    {% 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-2">
            <select id='co'>
                {% for co in companys %}
                    <option value='{{co.0}}'>{{co.1}}</option>
                {% endfor %}                
            </select>        
        </div>
        
        <label class="col-sm-1 control-label ">{% get_verbose_field_name form.instance 'name' %} </label>
        <div class="col-sm-2">{{ form.name }}</div>
        <label class="col-sm-1 control-label ">{% get_verbose_field_name form.instance 'awardcategory' %} </label>
        <div class="col-sm-2">{{ form.awardcategory }}</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 " style="margin-bottom:0px;padding-bottom:0px;">
        <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 'div_ids' %} </label>
        <div class='col-sm-2'>
            <div class="input-group">  
                {% ifequal user.id 1 %}
                    <input type="text" class=' form-control' id="div_label" placeholder='所有战区'/>
                    <input type="hidden" id="div_id" />                    
                {% else %}
                    <select id='div_id'>
                        <option value=''>所有战区</option>
                        {% for o in saldivision %}
                            <option value='{{o.0}}'>{{o.1}}</option>
                        {% endfor %}                        
                    </select>
                {% endifequal %}
                <span class="input-group-btn"><button type="button" class="btn btn-success add-div">
                    <span class='glyphicon glyphicon-arrow-down'></span></button></span>
            
            </div>
        </div>

        <label class="col-sm-1 control-label ">{% get_verbose_field_name form.instance 'subdiv_ids' %} </label>
        <div class='col-sm-2'>
            <div class="input-group">
                <!--
                <input  type="text" class=' form-control' id="subdiv_label" placeholder='所有分区'/>
                <input type="hidden" id="subdiv_id" />
                -->
                <select  id="subdiv_id"><option>所有分区</option></select>
                <span class="input-group-btn"><button type="button" class="btn btn-success add-subdiv">
                    <span class='glyphicon glyphicon-arrow-down'></span></button></span>
            </div>
        </div>
       
    </div>

    <div class="form-group" style='padding-top:0px;margin-top:0px;'>
        <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-div" multiple="multiple">
                {% for o in div_ids %}
                    <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-subdiv" multiple="multiple">
                {% for o in subdiv_ids %}
                    <option value='{{o.0}}'>{{o.1}}</option>
                {% endfor %}        
            </select>        
        </div>
    </div>    


    



     <div class="form-group ">
        <label class="col-sm-1 control-label">
            <span title="经销商扫码" data-placement="top" data-toggle="tooltip">活动开始时间</span>
        </label>
        <div class='col-sm-2'> {{ form.tm_start }}</div>
        <label class="col-sm-1 control-label">
            <span title="经销商扫码" data-placement="top" data-toggle="tooltip">活动结束时间</span>
        </label>
        <div class='col-sm-2'> {{ form.tm_end }}</div>
        <label class="col-sm-1 control-label">
            <span title="公司发货" data-placement="top" data-toggle="tooltip">最早发货日期</span>
        </label>
        <div class='col-sm-2'> {{ form.dt_delivery }}</div>
        
        <label class="col-sm-1 control-label">{% get_verbose_field_name form.instance 'status' %}</label>
        <div class='col-sm-2'> {{ form.status }}</div>        
    </div>

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


{% endblock %}

{% block extra %}
    <div class="form-group " style="padding:15px;">
        <label class="col-sm-1 control-label">{% get_verbose_field_name form.instance 'package_unit' %}</label>
        <div class='col-sm-2'> {{ form.package_unit }}</div>

        <span><a type="button" class='btn btn-success add-rebate'>
                <span class='glyphicon glyphicon-plus' style='padding-right:5px;'></span>{% trans '添加扫码场景' %}
        </a></span>

        <a class="btn btn-primary btn-save pull-right" type="button" >
            {% trans '保存活动设置' %}
        </a>

    </div>
{% endblock %}

{% block fmset %}
<div id="empty-form" style="display:none;">
    <div id="id_channelrebate_promotion-__prefix__" class="row x_panel rebate" style="margin-left:2px;">
        <div class="col-sm-6 ">
            <div class="form-group ">
                <label class="col-sm-2 control-label">{% trans '扫码层级' %}</label>
                <div class='col-sm-10'> {{ formset.empty_form.level }}</div>
            </div>
            <div class="form-group ">
                {{formset.empty_form.id}}{{formset.empty_form.promotion}}{{formset.empty_form.pvals}}
                <label class="col-sm-2 control-label">{% trans '扫码类型' %}</label>
                <div class='col-sm-10'> {{ formset.empty_form.vtype_id }}</div>
            </div>

            <div class="form-group ">
                <label class="col-sm-2 control-label">{% trans '返利金额' %}</label>
                <div class='col-sm-2'> {{ formset.empty_form.val }}</div>

                <label class="col-sm-2 control-label">{% trans '距离限定' %}</label>
                <div class='col-sm-2'> {{ formset.empty_form.distance }}</div>

                <div class="col-sm-4">
                    <label class="control-label col-md-offset-2">{% trans '勾选删除当前扫码场景' %}</label>
                    <div class="pull-right"> {{ formset.empty_form.DELETE }}</div>
                </div>
            </div>
        </div>
        <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-2 control-label">{% trans '经销商层级返利' %}</label>
                    <div class="col-sm-4"><select class="sel-plv"></select></div>
                    <div class="col-sm-5"><input placeholder="层级返利金额" class="pval"></div>
                    <span class="input-group-btn"><button type="button" class="btn btn-success add-pval  pull-right">
                        <span class='glyphicon glyphicon-arrow-down'></span></button></span>
                </div>
                <div class="form-group">
                    <select class="select2_multiple form-control sel-plvs"  multiple="multiple"></select>
                </div>
        </div>
    </div>
</div>
<div id="formset">
    {{ formset.management_form }}
</div>


<script type="text/javascript">
    $(document).ready(function(){  
        $('.select2_multiple').on('dblclick','option',function(){
            $(this).remove();
        });
    });

</script>
{% endblock %}













