{% extends 'obj_form.html' %}
{% load i18n %}




{% block subtitle %}
<ol class="breadcrumb">
        <li>{% trans '宴会管理' %}</li>
        <li>{% trans '政策方案' %}</li>
</ol>
{% endblock %}



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

<style>
    #sel-1,#sel-2,#sel-3,#number1,#number2,#number3,#sel-1-table,#sel-2-table,#sel-3-table,#number1-table,#number2-table,#number3-table{    
        display:inline-block;
        width:60px;
    }
    #sel-1,#sel-2,#sel-1-table,#sel-2-table{
        width:70px;
    }
    #sel-3,#number3,#sel-3-table,#number3-table{
        width:100px;
    }
    #tb-grade input{
        margin:0px;
        padding:0px;
        
    }

    #tb-grade tbody td a.exp{
       color:black;
       background:#0066ff;
       padding:5px;
       border-radius:5px;
       cursor:pointer;    
    }
    #tb-grade tbody td span{
        display:inline-block;
    }
    
    #tb-grade tbody input{
        width:98%;
    }
   
    #sel-rg{
        width:100px;
    }

    
</style>


<script>

    $(document).ready(function () {
        $('#div-cfg .tpdng').css('margin-top','8px');  

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


        var unit=''
        $('#id_package_basis').on("change", function() {
            var p='';
            if($(this).val()=='3'){
                p='箱';
                unit='X';
                $('#tb-grade tbody tr').each(function() {
                    var a=$(this).find('td.exp-x').find('a');
                    a.text(a.text().replace(/P/g,"X"));            
                });                
            }else{
                p='瓶';
                unit='P';
                $('#tb-grade tbody tr').each(function() {
                    var a=$(this).find('td.exp-x').find('a');
                    a.text(a.text().replace(/X/g,"P"));            
                });                
            };

            $('#number1,#number2,#number3').attr('placeholder',p+'数');
            $('#unit-x').text(unit);
            
            $('#pgk').text(p);            

        });
        $('#id_depend_on_product').on('change',function(){
            conditionChange();        
        });

        $('#id_package_basis').change();

        function conditionChange(){
            var hd='',html='<th class="exp-x">扫码数量</th><th class="exp-z">扫码数量</th>';
            if ($('#id_depend_on_product').val()==1){
                $("#sel-product option").each(function(){                
                    hd=hd+"<th product_id='"+$(this).val()+"'>"+$(this).text()+"</th>"                   
                });        
            };            
            if (hd==''){
                html=html+'<th product_id="0">奖励</th>';
            }else{
                html=html+hd;
            }            
            $('#tb-grade thead').html('<tr>'+html+'</tr>');
            $('#tb-grade tbody').html('');
        };

        function rangeChange(){
            var html='';
            var z='<span style="margin-left:4px;margin-right:4px;color:green;font-weight:bold;">Z</span>';
            var u='<span id="unit-x" style="margin-left:4px;margin-right:4px;color:green;font-weight:bold;">'+unit+'</span>'
            if($('#sel-rg').val()=='range'){
                html='<input  id="number1" class="form-control" placeholder="箱数"/>'+
                    '<select id="sel-1" class="form-control">'+
                        '<option value="＜"  >小于</option>'+                        
                        '<option value="≤" >小于等于</option>'+
                    '</select>'+u+                    
                    '<select id="sel-2"  class="form-control" >'+
                        '<option value="＜"  >小于</option>'+                         
                        '<option value="≤" >小于等于</option>'+
                    '</select>'+                                       
                    '<input id="number2"  class="form-control" placeholder="箱数"/>'+ 
                    '<span style="display:inline-block;width:60px;"></span>'+
                    '<input  id="number1-table" class="form-control" placeholder="桌数"/>'+
                    '<select id="sel-1-table" class="form-control">'+
                        '<option value="＜"  >小于</option>'+                        
                        '<option value="≤" >小于等于</option>'+
                    '</select>'+z+                    
                    '<select id="sel-2-table"  class="form-control" >'+
                        '<option value="＜"  >小于</option>'+                         
                        '<option value="≤" >小于等于</option>'+
                    '</select>'+
                    '<input id="number2-table"  class="form-control"  placeholder="桌数"/>'                    

            }else{
                html=u+
                    '<select id="sel-3"  class="form-control" >'+
                        '<option value="＞"  >大于</option>'+
                        '<option value="≥" >大于等于</option>'+
                    '</select>'+
                    '<input id="number3"   class="form-control" placeholder="箱数" />'+   
                    '<span style="display:inline-block;width:60px;"></span>'+
                    z+
                    '<select id="sel-3-table"  class="form-control" >'+
                        '<option value="＞"  >大于</option>'+
                        '<option value="≥" >大于等于</option>'+
                    '</select>'+
                    '<input id="number3-table"   class="form-control" placeholder="桌数" />'                   

            }
            $('#span-equation').html(html);

        };
        rangeChange();
        $('#sel-rg').on('change',function(){            
            rangeChange()
        });


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

        
        $('.btn-save').click(function () {
             var ps=[],gs=[];
             $("#sel-product option").each(function(){                
                 ps.push({
                     id:$(this).val(), 
                     name:$(this).text()
                 })                   
             });    
            
            $('#tb-grade tbody tr').each(function(rowIndex, rowElement) {
                var d={exp_x:'',exp_z:'',vals:[]}

                $(this).find('td').each(function(cellIndex, cellElement) {
                    if($(this).hasClass("exp-x")){
                        d.exp_x=$(this).find('a.exp').text();                    
                    }else{
                        if($(this).hasClass("exp-z")){
                            d.exp_z=$(this).text();
                        }else{
                            d.vals.push({
                                product_id:$(this).find('input').attr('product_id'),  
                                product_name:$(this).find('input').attr('product_name'),
                                value:$(this).find('input').val()
                            })
                        }
                    }                    
                });                
                gs.push(d);              

            });
            
            $('#products').val(JSON.stringify(ps));  
            
            $('#bonus_grades').val(JSON.stringify(gs));

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

        });
        

        
		$('#product_label').css('z-index',1);


        $('#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;
            }
        });

        $('.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>");                    
                    conditionChange();
                }
            };
        });


        
        $('.add-grade').click(function(){              
            if(can_add_grade()){
                var html='', u='',ex_x='';
                var unit_z='Z',ex_z='';
                if($('#id_bonus_type').val()==1){
                    u='元'                
                };
                if($('#sel-rg').val()=='range'){
                    ex_x="<td class='exp-x'><a class='exp' title='双击删除整行'>"+    
                        $('#number1').val().toString()+$('#sel-1').val()+unit+
                        ' and '+unit+
                        $('#sel-2').val().toString()+$('#number2').val().toString()+"</a></td>"; 
                    ex_z="<td class='exp-z'>"+    
                        $('#number1-table').val().toString()+$('#sel-1-table').val()+unit_z+
                        ' and '+unit_z+
                        $('#sel-2-table').val().toString()+$('#number2-table').val().toString()+"</td>"; 

                }else{
                    ex_x="<td class='exp-x'><a class='exp' title='双击删除整行'>"+                           
                        unit+$('#sel-3').val()+$('#number3').val().toString()+"</a></td>";
                    ex_z="<td class='exp-z'>"+                           
                        unit_z+$('#sel-3-table').val()+$('#number3-table').val().toString()+"</td>";
                }; 

                $("#tb-grade thead tr th").each(function(){
                     if($(this).hasClass("exp-x")){
                        html=html+ex_x;
                     }else{
                         if($(this).hasClass("exp-z")){
                            html=html+ex_z;
                         }else{
                            pid=$(this).attr('product_id');                                     
                            html=html+"<td>"+
                                "<input type='number' class='form-control' product_id='"+pid+"' product_name='"+$(this).text()+"' />"+
                                "</td>";
                         }
                    }  
                 });

                $('#tb-grade tbody').append("<tr>"+html+"</tr>");
            } else{
                toastr.error("输入框填写不完整！", "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;                
            }
            
        });
        

        $('#tb-grade').on('dblclick','a.exp',function(){
            var msg = "您确定要删除这行设置吗？\n\n请确认！";                 
            if (confirm(msg)==true){
                $(this).closest('tr').remove();
            };        
        });
        function can_add_grade(){
            var b=false;
            if($('#sel-rg').val()=='range'){
                if ($.isNumeric($('#number1').val()) && $.isNumeric($('#number2').val())){
                    b=true;
                }            
            }else{
                if($.isNumeric($('#number3').val())){
                    b=true;
                }            
            }
            return b
        } 
		
        // 消费者扫码策略
		$('#award_label').css('z-index',1);

        $('#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;
            }
        });
        
		$('#scan_product_label').css('z-index',1);

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

        $("#consumer_scan_strategy_select").change(function(){
            var v=$(this).val();
            // 如果是单个消费者中奖
            if(v=='consumer_win'){
                $("#input_scan_num").attr('readonly','readonly');
                $("#input_scan_num").val('1');
            }else{
                $("#input_scan_num").removeAttr('readonly');
            }
        })

        $("#btn_add_condition").click(function(){
            var condition = $("#consumer_scan_strategy_select").val()
            var condition_label = $('#consumer_scan_strategy_select').find('option:selected').text();
            var num = $("#input_scan_num").val()
            var award_id = $("#award_id").val()
            var award_label = $("#award_label").val()
            var product_id = $("#scan_product_id").val()
            var product_label = $("#scan_product_label").val()
            var strategy = get_consumer_scan_strategy()
            if(!num || !award_id){
                alert('请填写完整信息')
                return;
            }
            for(var s of strategy){
                if(s.condition === condition){
                    alert('该条件已添加')
                    return
                }
            }
            if(!product_id){
                product_id = 0
                product_label = '全部'
            }
            var data = {condition, condition_label, num, award_id, award_label, product_id, product_label}
            add_tbody_strategy(data)
            $("#consumer_scan_strategy").val(JSON.stringify(get_consumer_scan_strategy()))
        })

        function add_tbody_strategy(data){
            $("#tbody_strategy").append(`
                <tr data-strategy='${JSON.stringify(data)}' class="consumer_scan_strategy_tr">
                    <td class='scan-condition'>
                        当${data.condition_label}达到${data.num}次
                    </td>    
                    <td class="scan-product">
                        ${data.product_label}
                    </td>
                    <td class="scan-award">
                        ${data.award_label}
                    </td>
                    <td>
                        <a style="color: #f00;" onclick="del_consumer_scan_strategy_tr(this)" href="javascript:">删除</a>
                    </td>
                </tr>
            `)
        }

        var strategies = $("#consumer_scan_strategy").val().replaceAll("'",'"')
        if(strategies){
            for(var s of JSON.parse(strategies)){
                add_tbody_strategy(s)
            }
        }
    })

    function del_consumer_scan_strategy_tr(e){
        // 获取当前按钮的父级元素
        var parentRow = $(e).closest('.consumer_scan_strategy_tr');
        console.log(parentRow)
        // 删除父级元素
        parentRow.remove();
        $("#consumer_scan_strategy").val(JSON.stringify(get_consumer_scan_strategy()))
    }


    function get_consumer_scan_strategy(){
        var arr = []
        var trs = $(".consumer_scan_strategy_tr")
        for(var tr of trs){
            arr.push($(tr).data('strategy'))
        }
        return arr
    }

</script>




<div class="form-group">
    <label class="col-sm-1 control-label ">政策名称</label>
    <div class="col-sm-5">{{ form.name }}</div>
    <label class="col-sm-1 control-label ">扫码记数</label>
    <div class="col-sm-5">{{ form.package_basis }}</div>        
</div>

<div class="form-group">
    <label class="col-sm-1 control-label ">奖励类型</label>
    <div class="col-sm-5">{{ form.bonus_type }}</div>
    <label class="col-sm-1 control-label ">等级规则</label>
    <div class="col-sm-5">{{ form.criteria }}</div>
       
</div>


<div class="form-group">
    <label class="col-sm-1 control-label ">扫码区域</label>
    <div class="col-sm-5">{{ form.location_constrain }}</div>

    <label class="col-sm-1 control-label ">开始日期</label>
    <div class="col-sm-2">{{ form.dt_start }}</div>
    <label class="col-sm-1 control-label ">结束日期</label>
    <div class="col-sm-2">{{ form.dt_end }}</div>   
</div>



<div class="form-group">
    <label class="col-sm-1 control-label ">产品限定</label>
    <div class='col-sm-11'>
        <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>
</div>

    

<div class="form-group" style='margin-top:-28px;margin-bottom:8px;'>
    <div class='col-sm-11 col-md-offset-1'>
        <select class="select2_multiple form-control" id="sel-product" multiple="multiple">
            {% for o in form.instance.products %}
                <option value='{{o.id}}'>{{o.name}}</option>
            {% endfor %}                                     
        </select>        
    </div>
</div>

<div class='clearfix' ></div>

<div class='form-group' id='div-cfg' style='margin-top:8px;'>
    <input id='equation' type='hidden' />   
    
    <div class='col-sm-1  tpdng'>
        <span>奖励设置</span>
    </div>

   
    <div   class='col-sm-1'>
        {{form.depend_on_product}}
    </div>
    
  
    <div class='col-sm-1' >        
        <select class='form-control' id='sel-rg'>
            <option value='range'>在...之间</option>
            <option value='greater'>大于</option>
        </select>
    </div>

    <div class='col-sm-7' >        
        <span id='span-equation'></span>   
        <span class="input-group-btn" style="display:inline-block;">
            <button type="button" class="btn btn-success add-grade">
                <span class='glyphicon glyphicon-arrow-down'></span>
            </button>            
        </span>         
    </div>    
    

   
    <div class='col-sm-2'>
        <span id='dw' class='tpdng'>
            单位：{% ifequal form.instance.bonus_type 1%}元{% endifequal %}
        </span>
        <a class="btn btn-primary btn-save pull-right" type="button" >保存</a>
    </div>

        
</div>

<input id='grades' name='grades' type='hidden'/>
<input id='bonus_grades' name='bonus_grades' type='hidden'/>
<input id='consumer_scan_strategy' name='consumer_scan_strategy' type='hidden' value="{{form.instance.consumer_scan_strategy}}"/>
<input id='products' name='products' type='hidden' />


<div class="table-responsive">
    <table id='tb-grade' class='table table-bordered table-condensed table-hover' style='width:100%'>
        <thead><tr>
        <th class='exp-x'>扫码数量</th>
        <th class='exp-z'>宴席桌数</th>
        {% if form.instance.products %}
            {% for p in form.instance.products %}
                <th product_id='{{p.id}}'>{{p.name}}</th>                
            {% endfor %}            
        {% else %}             
            <th product_id='0'>奖励</th>
        {% endif %}
        </tr></thead>
        <tbody>
            {% for g in form.instance.bonus_grades %}
                <tr>
                <td class='exp-x'><a class='exp' title='双击删除整行'>{{g.exp_x}}</td>                
                <td class='exp-z'>{{g.exp_z}}</td>

                {% for v in g.vals %}
                    <td>
                        <input type='number' product_id='{{v.product_id}}' product_name='{{v.product_name}}' value='{{v.value}}' />                        
                    </span></td>
                {% endfor %}
                </tr>
            {% endfor %}        
        </tbody>
    </table>
</div>

<div class="table-responsive">
    <table id='tb-consumer-scan-strategy' class='table table-bordered table-condensed table-hover' style='width:100%'>
        <thead>
            <tr>
                <th>触发条件</th>
                <th>触发产品</th>
                <th>奖励经销商</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="tbody_strategy">
            <tr>
                <td class='scan-condition'>
                    <span>当</span>
                    <select style="display: inline-block; width: 200px; margin-left: 10px;" id="consumer_scan_strategy_select">
                        <option value="consumer_win">单个消费者中奖</option>
                        <option value="consumer_win_total">消费者中奖累计</option>
                    </select>
                    <span style="margin-left: 10px;">达到</span>
                    <input id="input_scan_num" type='number' value='1' style="display: inline-block; width: 80px; margin-left: 10px;" readonly="readonly"/>
                    <span style="margin-left: 10px;">次</span>
                </td>           
                <td class="scan-product">
                    <input type="text" class="form-control" id="scan_product_label" placeholder="产品名称">
                    <input type="hidden" id="scan_product_id" />
                </td>
                <td class="scan-award">
                    <input type="text" class="form-control" id="award_label" placeholder="奖品名称">
                    <input type="hidden" id="award_id" />
                </td>
                <td>
                    <button type="button" class="btn btn-success" id="btn_add_condition">
                        <span class='glyphicon glyphicon-arrow-down'></span>
                    </button>     
                </td>
            </tr>    
        </tbody>
    </table>
</div>


{% endblock %}
