{% 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;
    }
	
	.input-select{
        display: inline-block;
        width: 100px;
        border: none;
        border-bottom: 1px solid gray;
	}
	
	.btn-award-copy{
		margin-left: 10px
	}
</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-10">
        <input type="text"  class="form-control" placeholder="号段（非必填、适当使用可提升效率）" id="input_code_range">
    </div>
</div>
<div class="form-group ">
    <label class="col-sm-2 control-label"></label>
    <div class="col-sm-2">
        <input type="button" id="prizebutton" 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">
					<label for="lottery_method_1">
						<input type="radio" class="methodRadio" name="lottery_method" value="1" id="lottery_method_1" checked disabled/> 随机布奖
					</label>
					<label for="lottery_method_3">
						<input type="radio" class="methodRadio" name="lottery_method" value="3" id="lottery_method_3" disabled/> 按箱分配数量布奖（简单模式）
					</label>
					<label for="lottery_method_2">
						<input type="radio" class="methodRadio" name="lottery_method" value="2" id="lottery_method_2" disabled/> 按箱分配数量布奖（专业模式）
					</label>
					<label for="lottery_method_4">
						<input type="radio" class="methodRadio" name="lottery_method" value="4" id="lottery_method_4" disabled/> 箱标布奖
					</label>
					
					<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>
							AB标选择：
							<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
    function startLottery() {
        var input = $("#input_code").val();
        var type = $("#select_type").val();
        //if (input.length >= 12) {
        queryBatch(input)
        //}
        if (isnow) {
             $("#prizebutton").attr("disabled","disabled");    //按钮一次限制
                     }
    }

    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="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: '/inventory/batch/query/',
            data: {
                batch_id,
				code_range: $("#input_code_range").val()
            },
            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();
					
					var blength = batch_id.split(',').length
					if(blength>1){
						//$("#lottery_method_3").parent().hide()
						//$("#lottery_method_2").parent().hide()
					}
                }
            }
        })
    }

    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;
						awards.push({id:0, name: '谢谢惠顾'})
                        var html = ''
                        for (let i = 0; i < awards.length; i++) {
                            let a = awards[i];
                            html += renderAwardRowHtml(a,0)
                        }
                        $("#activty_awards").html(html);
                        $("#activty_awards_choose").show();
						$(".methodRadio").removeAttr('disabled')
                    }
                }
            })
        }
        else {
            $("#activty_awards_choose").hide();
            $("#activty_awards").empty();
        }
    }
	
	$(".methodRadio").change(function(){
		console.log(this.value);
		if(this.value === '2'){
			showMethod2Form()
		}
		else if(this.value === '3'){
			hideMethod2Form()
			$("#alertMethod2").show()
		}
		else if(this.value === '4'){
			hideMethod2Form()
		}
		else{
			hideMethod2Form()
		}
	})
	
	function showMethod2Form(){
		$("#alertMethod2").show();
		$(".group-select").show();
		$(".input-qty-upper").show();
		$(".btn-award-copy").show();
	}
	
	function hideMethod2Form(){
		$("#alertMethod2").hide();
		$(".group-select").hide().val('');
		$(".input-qty-upper").hide().val('');
		$(".btn-award-copy").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 awards = [];
        var remark = $("#input_remark").val();
		var lotteryMethod = $('.methodRadio:checked').val();
		var abcode = $('.abcode:checked').val();
		var is_terminal_rebate =$('.is_terminal_rebate:checked').val();
        $('input[name="check_award"]:checked').each(function () {
            var award_id = $(this).val();
			var idx = $(this).data("idx");
            var num = $("#input-award-" + award_id+"-"+idx).val().trim();
            if (num === "") {
                num = "0"
            }
            var qty_upper = $("#input-qty-upper-" + award_id+"-"+idx).val().trim();
			if (qty_upper === "")
				qty_upper = "0"
            
			var group = $("#group-select-" + award_id+"-"+idx).val();
			
			var item = {
                award_id: parseInt(award_id),
                num: parseInt(num),
                qty_upper: parseInt(qty_upper),
				group,
				lotteried_num: 0
            }
			
            awards.push(item)
        });

        console.log(awards)
		//return
        if (batch_id && batch_id !== '') {
            if (activity_id && activity_id !== '') {

                if (awards.length > 0) {
                    let num = 0;
					
					var groups = []
					for (let i = 0; i < awards.length; i++) {
						var group = awards[i].group
						if(group && groups.indexOf(group) !== -1)
							continue
						num += awards[i].num
						if(group && lotteryMethod === '2')
							groups.push(group)
					}
					
                    if (num < 1) {
                        alert('奖品数量不能都为0！')
						return;
                    }
					
					var boxBottleNum = 0;
					if(lotteryMethod === '2' || lotteryMethod === '3'){
						boxBottleNum = parseInt( $("#alertMethod2 b").text());
						if(num>boxBottleNum){
							alert(`每箱设置奖项数量不能超过${boxBottleNum}！`)
							return;
						}
					
					}
					// 如果是箱标布奖
					if(lotteryMethod === '4'){
						var boxNum = parseInt($("#input_box_num").val());
						if(num>boxNum){
							alert(`设置奖项数量不能超过${boxNum}！`)
							return;
						}
					}
                    console.log(batch_id,activity_id,awards);
                    awards = JSON.stringify(awards)
					var code_range = $("#input_code_range").val()
                    $.ajax({
                        url:'/sales/activity/lottery/',
                        type:'post',
                        data:{
                            batch_id,
                            activity_id,
                            awards,
                            remark,
							lotteryMethod,
							boxBottleNum,
							abcode,
                            is_terminal_rebate,
							code_range
                        },
                        success:function(res){
                            $("#loading").hide();
                            if(res.e === ''){
                                alert('布奖成功！');
                                $.RefreshContent('/sales/lotteryseeds/');
                            }
                            else{
                                alert(res.e)
                            }
                            isDraw = false;
                        }
                    })
                }
                else {
                    alert('请选择奖品!')
                }
            }
            else {
                alert('请选择活动!')
            }
        }

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

    }
	
	function renderAwardRowHtml(a, idx){
		return ` 
			<p>
				<label>
					<input type="checkbox" name='check_award' value='${a.id}' data-idx="${idx}"> ${a.name}
				</label>
				<input type="number" placeholder="奖品数量" class="input-num" id="input-award-${a.id}-${idx}">
				<input type="number" placeholder="奖品上限" class="input-num input-qty-upper" id="input-qty-upper-${a.id}-${idx}" style="display: none">
				<select class="input-select group-select" id="group-select-${a.id}-${idx}" style="display: none">
					<option value="">奖品分组</option>
					<option value="A">A</option>
					<option value="B">B</option>
					<option value="C">C</option>
					<option value="D">D</option>
					<option value="E">E</option>
					<option value="F">F</option>
					<option value="G">G</option>
					<option value="H">H</option>
				</select>
				<input type="button" class="btn-award-copy" onclick="addAwardRow(this, ${idx}, ${a.id},'${a.name}')" style="display: none" value="复制"/>
			</p> `
	}
	
	function addAwardRow(e, idx, id, name){
		var html = renderAwardRowHtml({id,name},idx+1)
		//console.log(html)
		$("#activty_awards").append(html)
		showMethod2Form()
		$(e).attr("disabled",true)
	}
	
    {#$("#but_sub").attr({"disabled":"disabled"});#}
</script>
{% endblock %}