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

{% block subtitle-1 %}
{% trans "营销活动" %}
{% endblock %}
{% block subtitle-2 %}
{% trans "奖池布奖" %}
{% endblock %}


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

<style>
    input[type=radio],
    input[type=checkbox] {
        display: inline-block;
        width: auto;
        height: auto;
        border: none;
        box-shadow: none;
    }

    .input-num {
        display: inline-block;
        width: 100px;
        border: none;
        border-bottom: 1px solid gray;
    }
</style>

<div class="form-group ">
    <label class="col-sm-2 control-label">箱标或者订单号</label>
    <div class="col-sm-10">
        <input type="text"  class="form-control" placeholder="箱标或者订单号" id="input_code">
    </div>
</div>
<div class="form-group ">
    <label class="col-sm-2 control-label"></label>
    <div class="col-sm-2">
        <input type="button" id="test" value="开始布奖" class="btn btn-primary" onclick="startLottery();">
    </div>
</div>

<div id="con-batch" class="table-responsive" style="margin-top: 20px;display: none;">
    <p>请选择一个订单</p>
    <table class="table table-bordered table-condensed table-hover">
        <tbody id="table-batch">
            <tr class="b">
                <td>选择</td>
                <td>时间</td>
                <td>单据类型</td>
                <td>单据编号</td>
                <td>发货公司</td>
                <td>客户名称</td>
            </tr>
        </tbody>
    </table>
    <div>
        <input type="button" value="选择订单" class="btn btn-default btn-sm" onclick="chooseBatch();" style="width:70px">
    </div>

    <div class="panel panel-default" style="margin-top: 20px;display: none;" id="lootery-con">
        <div class="panel-heading">布奖操作</div>
        <div class="panel-body">
            <div class="form-group ">
                <label class="col-sm-1 control-label">箱数</label>
                <div class="col-sm-11">
                    <input id="input_box_num" class="form-control" type="text" value="" disabled>
                </div>
            </div>
{#            <div class="form-group ">#}
{#                <label class="col-sm-1 control-label">瓶数</label>#}
{#                <div class="col-sm-11">#}
{#                    <input id="input_bottle_num" class="form-control" type="text" value="220" disabled>#}
{#                </div>#}
{#            </div>#}
            <div class="form-group ">
                <label class="col-sm-1 control-label">选择活动</label>
                <div class="col-sm-11">
                    <select name="rule_category" id="select_activites" class="form-control"
                        onchange="chooseActivities(this);">
                        <option value="">请选择</option>
                        {% for a in activites %}
                        <option value="{{a.id}}">{{a.name}}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="form-group ">
                <label class="col-sm-1 control-label">选择方案</label>
                <div class="col-sm-11">
                    <select name="rule_category1" id="select_promotions" class="form-control"
                        >
                        <option value="">请选择</option>
                        {% for a in promotions %}
                        <option value="{{a.id}}">{{a.name}}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-1 control-label">布奖方式</label>
                <div class="col-sm-11">
                    <input type="radio" class="methodRadio" name="lottery_method" value="1" checked /> 随机布奖
{#                    <input type="radio" class="methodRadio" name="lottery_method" value="2"/> 按箱分配数量布奖#}
					
{#					<div class="alert alert-info" id="alertMethod2" style="display:none;margin-top:10px">您每箱最大可布奖的数量不能超过<b></b>个</div>#}
                </div>
            </div>
            <div class="form-group" id="activty_awards_choose" style="display: none;">
                <label class="col-sm-1 control-label">奖品选择</label>
                <div class="col-sm-11" id="activty_awards">

                </div>
            </div>
            <div class="form-group ">
                <label class="col-sm-1 control-label">备注</label>
                <div class="col-sm-11">
                    <input type="text" id="input_remark" placeholder="输入备注"/>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-1 control-label">系统管理员选项</label>
                <div class="col-sm-11">
					<div>
						提示：非专业人员无需关注此项
						<input type="button" value="显示" class="btn btn-default btn-sm" style="width:50px" id="btn_showadminform"/>
					</div>
					<div id="adminform" style="display:none">
						<div>
							标签类型选择：
							<input type="radio" class="abcode" name="abcode" value="A" checked /> A标
							<input type="radio" class="abcode" name="abcode" value="B"/> B标
{#                            消费者扫码终端是否返利：#}
{#                            <input type="radio" class="is_terminal_rebate" name="is_terminal_rebate" value="1"  /> 是#}
{#                            <input type="radio" class="is_terminal_rebate" name="is_terminal_rebate" value="0" checked/>否#}
						</div>
					</div>
				</div>
            </div>
            <!-- <div class="form-group ">
                <label class="col-sm-1 control-label"></label>
                <div class="col-sm-11">
                    <input type="checkbox" id="check_x" /> 箱码参与布奖
                </div>
            </div> -->
            <div class="form-group" style="margin-top:20px">
                <label class="col-sm-1 control-label"></label>
                <div class="col-sm-11">
                    <input type="button" id="but_sub" value="布奖" class="btn btn-danger btn-sm"
                        style="width:50px">
                </div>
            </div>
        </div>
    </div>


</div>


<script>
    $(document).ready(function () {

		$("#btn_showadminform").click(function(){
			$(this).hide();
			$("#adminform").show();
		})
    });


    var isnow=true
    {#$("#exportCameraButton").removeAttr("disabled");#}
    function startLottery() {
        var input = $("#input_code").val();
        var type = $("#select_type").val();
        if (input.length >= 12) {
            queryBatch(input)
        }
        if (isnow) {
             $("#test").attr("disabled","disabled");    //按钮一次限制
                     }
    }

    function queryBatch(code) {
        $.ajax({
            url: '/sales/batch/batch_terminal/',
            data: {
                code
            },
            success: function (res) {
                if (res.e === '') {
                    var batch = res.batch;
                    var html = '';
                    for (let i = 0; i < batch.length; i++) {
                        let b = batch[i];
                        html += `
                            <tr>
                                <td>
                                    <input type="checkbox" name="batch_id" multiple value="${b.id}" />
                                </td>
                                <td>${b.tm}</td>
                                <td>${b.vtype}</td>
                                <td>${b.now_code}</td>
                                <td>${b.comp_fr}</td>
                                <td>${b.comp_to}</td> 
                            </tr> `
                    }
                    $("#table-batch").append(html)
                    $("#con-batch").show();
                }
            }
        })
    }


    function chooseBatch() {
        {#var batch_id = $("input[name='batch_id']:checked").val();#}
        {#    console.log(batch_id)#}
        var batch_id = '';
        $("input[name='batch_id']:checked").each(function () { //遍历，将所有选中的值放到数组中
            {#console.log($(this).val())#}
            {#batch_id.push($(this).val());#}
            batch_id+=$(this).val()+',';
        });
        if (batch_id) {
            queryCode(batch_id);
        }
    }

    function queryCode(batch_id) {
        $.ajax({
            url: '/sales/batch/batch_terminal/',
            data: {
                batch_id
            },
            success: function (res) {
                if (res.e === '') {
                    var box_num = res.box_num;
                    {#var bottle_num = res.bottle_num#}
                    $("#input_box_num").val(box_num);
                    {#$("#input_bottle_num").val(bottle_num);#}
					{#$("#alertMethod2 b").text(bottle_num/box_num);#}
                    $("#lootery-con").show();
                }
            }
        })
    }

    function chooseActivities(ele) {
        let activity_id = $(ele).val();
        if (activity_id !== '') {
            $(ele).attr('disabled', 'disabled')
            $.ajax({
                url: '/sales/activity/awards/',
                data: {
                    activity_id
                },
                success: function (res) {
                    $(ele).removeAttr('disabled')

                    console.log(res);
                    if (res.e === '') {
                        var awards = res.awards;
                        var html = ''
                        for (let i = 0; i < awards.length; i++) {
                            let a = awards[i];
                            html += ` 
                            <p>
                                <label>
                                    <input type="checkbox" name='check_award' value='${a.id}'> ${a.name}
                                </label>
                                <input type="number" placeholder="请输入数量" class="input-num" id="input-award-${a.id}">
                            </p> `
                        }
                        $("#activty_awards").html(html);
                        $("#activty_awards_choose").show();
                    }
                }
            })
        }
        else {
            $("#activty_awards_choose").hide();
            $("#activty_awards").empty();
        }
    }
	
	$(".methodRadio").change(function(){
		console.log(this.value);
		if(this.value === '2'){
			$("#alertMethod2").fadeIn();
		}
		else{
			$("#alertMethod2").hide();
		}
	})


    $("#but_sub").click(debounce(lottery, 300));
    function debounce(fn, delay) {
            let timer;
            return function () {
                if (timer) {
                    clearTimeout(timer)
                }
                console.log(this)
                timer = setTimeout(() => {
                    fn.call(this)
                }, delay)
            }
    }

    var isDraw=false;
    function lottery() {
        if (isDraw) {
             return;
                     }
        isDraw = true;


        var batch_id = '';
        $("input[name='batch_id']:checked").each(function () { //遍历，将所有选中的值放到数组中
            {#console.log($(this).val())#}
            {#batch_id.push($(this).val());#}
            batch_id+=$(this).val()+',';
        });
        var activity_id = $("#select_activites option:selected").val();
        var promotions_id = $("#select_promotions option:selected").val();
        var awards = [];
        var remark = $("#input_remark").val();
        $('input[name="check_award"]:checked').each(function () {
            var award_id = $(this).val();
            var num = $("#input-award-" + award_id).val().trim();
            if (num === "") {
                num = "0"
            }
            awards.push({
                award_id: parseInt(award_id),
                num: parseInt(num)
            })
        });
		var lotteryMethod = $('.methodRadio:checked').val();
		var abcode = $('.abcode:checked').val();
		{#var is_terminal_rebate =$('.is_terminal_rebate:checked').val();#}

		console.log('abcode')
		console.log(abcode)
        {#console.log(is_terminal_rebate)#}

        if (batch_id && batch_id !== '') {
            if (activity_id && activity_id !== '') {

                if (awards.length > 0) {
                    let num = 0;
                    for (let i = 0; i < awards.length; i++) {
                        num += awards[i].num
                    }
                    if (num < 1) {
                        alert('奖品数量不能都为0！')
						return;
                    }
					var boxBottleNum = 0;
					if(lotteryMethod === '2'){
						boxBottleNum = parseInt( $("#alertMethod2 b").text());
						if(num>boxBottleNum){
							alert(`每箱设置奖项数量不能超过${boxBottleNum}！`)
							return;
						}
					
					}
                    console.log(batch_id,activity_id,awards,promotions_id);
                    awards = JSON.stringify(awards)
                    $.ajax({
                        url:'/sales/activity/PromotionSeeds_lottery/',
                        type:'post',
                        data:{
                            batch_id,
                            activity_id,
                            awards,
                            remark,
							lotteryMethod,
							boxBottleNum,
							abcode,
                            promotions_id,
                            {#is_terminal_rebate#}
                        },
                        success:function(res){
                            $("#loading").hide();
                            if(res.e === ''){
                                alert('布奖成功！');
                                $.RefreshContent('/sales/promotionseeds/');
                            }
                            else{
                                alert(res.e)
                            }
                            isDraw = false;
                        }
                    })



                }
                else {
                    alert('请选择奖品!')
                }
            }
            else {
                alert('请选择活动!')
            }
        }

        else {
            alert('请选择订单')
        }

    }
    {#$("#but_sub").attr({"disabled":"disabled"});#}
</script>
{% endblock %}