{% 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" maxlength="50" 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" 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">
                    <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">
                    <input type="checkbox" id="check_x" /> 箱码参与布奖
                </div>
            </div> -->
            <div class="form-group ">
                <label class="col-sm-1 control-label"></label>
                <div class="col-sm-11">
                    <input type="button" value="布奖" class="btn btn-danger btn-sm" onclick="lottery();"
                        style="width:50px">
                </div>
            </div>
        </div>
    </div>


</div>


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


    });


    function startLottery() {
        var input = $("#input_code").val();
        var type = $("#select_type").val();
        if (input.length >= 12) {
            queryBatch(input)
        }
    }

    function queryBatch(code) {
        $.ajax({
            url: '/inventory/batch/query/',
            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="radio" name="batch_id" value="${b.id}" /> 
                                </td>
                                <td>${b.tm}</td>
                                <td>${b.vtype}</td>
                                <td>${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();
        if (batch_id) {
            queryCode(batch_id);
        }
    }

    function queryCode(batch_id) {
        $.ajax({
            url: '/inventory/batch/query/',
            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();
		}
	})

    function lottery() {
        var batch_id = $("input[name='batch_id']:checked").val();
        var activity_id = $("#select_activites 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();

        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);
                    awards = JSON.stringify(awards)
                    $.ajax({
                        url:'/sales/activity/lottery/',
                        type:'post',
                        data:{
                            batch_id,
                            activity_id,
                            awards,
                            remark,
							lotteryMethod,
							boxBottleNum
                        },
                        success:function(res){
                            if(res.e === ''){
                                alert('布奖成功！');
                                $.RefreshContent('/sales/lotteryseeds/');
                            }
                            else{
                                alert(res.e)
                            } 
                        }
                    })



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

    }

</script>
{% endblock %}