<link href="<?php echo $this->basePath('js/plugins/jquery-autocompleter/jquery.autocompleter.css'); ?>" rel="stylesheet">
<script src="<?php echo $this->basePath('js/plugins/jquery-autocompleter/jquery.autocompleter.min.js'); ?>"></script>
<div class="content-wrapper">
    <?php
    $form = $this->form;
    $form->prepare();

    $goodsForm = $this->goodsForm;
    $goodsForm->prepare();

    $form->get('salesOrderSn')->setAttributes([
        'placeholder' => $this->translate('销售单号')
    ]);

    $form->get('salesOrderInfo')->setAttributes([
        'placeholder' => $this->translate('备注')
    ]);

    ?>
    <?= $this->form()->openTag($form); ?>
    <section class="content-header">
        <?=$this->partial('layout/breadcrumb')?>

        <h1 class="pull-right">
            <a href="<?=$this->url('sales-order');?>" class="btn btn-default btn-sm"><i class="fa fa-arrow-left"></i> <?=$this->translate('返回销售订单列表')?></a>
            <button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-check"></i> <?=$this->translate('保存销售订单')?></button>
            <?=(isset($salesOrderInfo) ? $this->HelpUrl('salesOrderEdit') : $this->HelpUrl('salesOrderAdd'))?>
        </h1>
    </section>

    <section class="content">

        <div class="row">
            <div class="col-md-12">
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title"><?=(isset($salesOrderInfo) ? $this->translate('编辑销售订单') : $this->translate('添加销售订单'))?></h3>
                    </div>

                    <div class="box-body">
                        <?=$this->formElementErrors($form->get('dberp_csrf'), ['class'=>'error-message']); ?>
                        <div class="row">
                            <div class="col-xs-4 form-group">
                                <div class="col-sm-12">
                                    <?=$this->translate('销售单号')?><span class="must_add_value">*</span>
                                    <?= $this->formElement($form->get('salesOrderSn')); ?>
                                    <?= $this->formElementErrors($form->get('salesOrderSn'), ['class'=>'error-message']); ?>
                                </div>
                            </div>

                            <div class="col-xs-4 form-group">
                                <div class="col-sm-12">
                                    <?=$this->translate('客户')?><span class="must_add_value">*</span>
                                    <?= $this->formElement($form->get('customerId')); ?>
                                    <?= $this->formElementErrors($form->get('customerId'), ['class'=>'error-message']); ?>
                                </div>
                            </div>

                            <div class="col-xs-4 form-group">
                                <div class="col-sm-12">
                                    <?=$this->translate('收款方式')?><span class="must_add_value">*</span>
                                    <?= $this->formElement($form->get('receivablesCode')); ?>
                                    <?= $this->formElementErrors($form->get('receivablesCode'), ['class'=>'error-message']); ?>
                                </div>
                            </div>

                        </div>

                        <div class="row">
                            <div class="col-xs-4 form-group">
                                <div class="col-sm-12">
                                    <?=$this->translate('客户联系人')?><span class="must_add_value">*</span>
                                    <?= $this->formElement($form->get('customerContacts')); ?>
                                    <?= $this->formElementErrors($form->get('customerContacts'), ['class'=>'error-message']); ?>
                                </div>
                            </div>

                            <div class="col-xs-4 form-group">
                                <div class="col-sm-12">
                                    <?=$this->translate('客户手机')?>
                                    <?= $this->formElement($form->get('customerPhone')); ?>
                                    <?= $this->formElementErrors($form->get('customerPhone'), ['class'=>'error-message']); ?>
                                </div>
                            </div>

                            <div class="col-xs-4 form-group">
                                <div class="col-sm-12">
                                    <?=$this->translate('客户座机')?>
                                    <?= $this->formElement($form->get('customerTelephone')); ?>
                                    <?= $this->formElementErrors($form->get('customerTelephone'), ['class'=>'error-message']); ?>
                                </div>
                            </div>

                        </div>

                        <div class="row">
                            <div class="col-xs-4 form-group">
                                <div class="col-sm-12">
                                    <?=$this->translate('客户地址')?><span class="must_add_value">*</span>
                                    <?= $this->formElement($form->get('customerAddress')); ?>
                                    <?= $this->formElementErrors($form->get('customerAddress'), ['class'=>'error-message']); ?>
                                </div>
                            </div>
                            <div class="col-xs-8 form-group">
                                <div class="col-sm-12">
                                    <?=$this->translate('备注')?>
                                    <?= $this->formElement($form->get('salesOrderInfo')); ?>
                                    <?= $this->formElementErrors($form->get('salesOrderInfo'), ['class'=>'error-message']); ?>
                                </div>
                            </div>

                        </div>

                        <?php
                        $goodsForm = $this->goodsForm;
                        ?>
                        <div class="box-header">
                            <h4 class="box-title"><?=$this->translate('销售商品')?></h4>
                            &nbsp;&nbsp;
                            <button type="button" class="btn btn-success btn-sm"  data-toggle="modal" onclick="addMoreGoods();"><i class="fa fa-plus"></i> <?=$this->translate('点击添加商品')?></button>
                            <?= $this->formElementErrors($goodsForm->get('goodsId'), ['class'=>'error-message']); ?>
                            <?= $this->formElementErrors($goodsForm->get('salesGoodsPrice'), ['class'=>'error-message']); ?>
                            <?= $this->formElementErrors($goodsForm->get('salesGoodsSellNum'), ['class'=>'error-message']); ?>
                            <?= $this->formElementErrors($goodsForm->get('salesGoodsAmount'), ['class'=>'error-message']); ?>
                        </div>
                        <div class="box-body table-responsive no-padding">
                            <table class="table table-hover">
                                <thead>
                                <tr>
                                    <th width="15%"><?=$this->translate('商品编号')?></th>
                                    <th><?=$this->translate('商品名称')?></th>
                                    <th><?=$this->translate('商品规格')?></th>
                                    <th width="5%"><?=$this->translate('单位')?></th>
                                    <th width="10%"><?=$this->translate('销售单价')?></th>
                                    <th width="10%"><?=$this->translate('销售数量')?></th>
                                    <th width="8%"><?=$this->translate('税金')?></th>
                                    <th width="10%"><?=$this->translate('销售总价')?></th>
                                    <th width="10%"><?=$this->translate('操作')?></th>
                                </tr>
                                </thead>

                                <?php
                                if(isset($salesOrderInfo)) {
                                    foreach ($this->salesOrderGoods as $goodsValue) {
                                        ?>
                                        <tr id="tr_id_<?=$goodsValue->getGoodsId()?>">
                                            <td>
                                                <input type="hidden" name="goodsId[]" value="<?=$goodsValue->getGoodsId()?>">
                                                <?=$this->escapeHtml($goodsValue->getGoodsNumber())?>
                                            </td>
                                            <td><?=$this->escapeHtml($goodsValue->getGoodsName())?></td>
                                            <td><?=$this->escapeHtml($goodsValue->getGoodsSpec())?></td>
                                            <td><?=$this->escapeHtml($goodsValue->getGoodsUnit())?></td>
                                            <td><input type="text" min="0" oninput="insertGoodsPrice(<?=$goodsValue->getGoodsId()?>);" id="sales_goods_price_<?=$goodsValue->getGoodsId();?>" name="salesGoodsPrice[]" class="form-control" value="<?=$this->erpCurrencyFormat($goodsValue->getSalesGoodsPrice(), '')?>" ></td>
                                            <td><input type="number" min="1" oninput="insertGoodsPrice(<?=$goodsValue->getGoodsId()?>);" id="sales_goods_sell_num_<?=$goodsValue->getGoodsId()?>" name="salesGoodsSellNum[]" class="form-control" value="<?=$goodsValue->getSalesGoodsSellNum()?>"></td>
                                            <td><input type="text" min="0" oninput="insertGoodsPrice(<?=$goodsValue->getGoodsId()?>);" id="sales_goods_tax_<?=$goodsValue->getGoodsId();?>" name="salesGoodsTax[]" class="form-control" value="<?=$this->erpCurrencyFormat($goodsValue->getSalesGoodsTax(), '')?>" ></td>
                                            <td><input type="text" oninput="sumAmount();" id="sales_goods_amount_<?=$goodsValue->getGoodsId()?>" name="salesGoodsAmount[]" class="form-control" value="<?=$this->erpCurrencyFormat($goodsValue->getSalesGoodsAmount(), '')?>"></td>
                                            <td>
                                                <button type="button" onclick="deleteGoods(<?=$goodsValue->getGoodsId()?>);" class="btn btn-danger"><?=$this->translate('删除')?></button>
                                            </td>
                                        </tr>
                                        <?php
                                    }
                                }
                                ?>

                                <tr id="tr-end">
                                    <td colspan="7"></td>
                                    <td colspan="2"><b><?=$this->translate('销售金额合计')?>：</b><span id="order-amount"><?=(isset($salesOrderInfo) ? $this->erpCurrencyFormat($salesOrderInfo->getSalesOrderAmount(), '') : 0)?></span></td>
                                </tr>
                            </table>
                        </div>

                    </div>
                    <div class="box-footer">
                        <?=$this->formElement($form->get('dberp_csrf')); ?>
                        <button type="submit" class="btn btn-primary col-md-offset-4"><i class="fa fa-check"></i> <?=$this->translate('保存销售订单')?></button>
                    </div>
                </div>


            </div>
        </div>

    </section>
    <?= $this->form()->closeTag(); ?>

    <div class="modal fade" id="modalDefault">
        <div class="modal-dialog" style="width: 800px;" id="addGoodsListBody">

        </div>

    </div>

</div>

<script>
    $(document).ready(function() {
        $("#<?=$form->getName()?>").validate({
            rules: {
                salesOrderSn: {
                    required: true
                },
                customerId: {
                    required: true,
                    min: 1
                },
                receivablesCode: {
                    required: true
                },
                customerAddress: {
                    required: true
                },
                customerContacts: {
                    required: true
                }
            },
            messages: {
                salesOrderSn: {
                    required: "<?=$this->translate('销售单号不能为空！')?>"
                },
                customerId: {
                    required: "<?=$this->translate('请选择客户！')?>",
                    min: "<?=$this->translate('请选择客户！')?>"
                },
                receivablesCode: {
                    required: "<?=$this->translate('请选择收款方式！')?>"
                },
                customerAddress: {
                    required: "<?=$this->translate('请填写客户地址！')?>"
                },
                customerContacts: {
                    required: "<?=$this->translate('请输入联系人！')?>"
                }
            },
            submitHandler: function(form) {
                if(typeof($("input[name='goodsId[]']").val()) == "undefined") {
                    layer.msg('<?=$this->translate('请添加销售商品！')?>');
                    return false;
                }
                form.submit();
            }
        });
    });

    $('#customerId').change(function () {
        $.post("<?= $this->url('customer', ['action' => 'customerIdSearch']);?>", {customerId: $(this).val()}, function (data) {
            if(data.state == 'ok') {
                $('#customerContacts').val(data.result.customerContacts);
                $('#customerPhone').val(data.result.customerPhone);
                $('#customerTelephone').val(data.result.customerTelephone);
                $('#customerAddress').val(data.result.regionValues+data.result.customerAddress);
            } else {
                $('#customerContacts').val('');
                $('#customerPhone').val('');
                $('#customerTelephone').val('');
                $('#customerAddress').val('');
            }
        });
    });

    function addSelectGoods (goodsId) {
        if(goodsId == '') {
            layer.msg('<?=$this->translate('请填写需要添加的商品名称！')?>');
        } else {
            var insertState = true;
            $("input[name='goodsId[]']").each(function () {
                if($(this).val() == goodsId) {
                    insertState = false;
                }
            });
            if(!insertState) {
                layer.msg('<?= $this->translate('该商品已经添加！')?>');
                return false;
            }

            $.post("<?= $this->url('goods', ['action' => 'goodsIdSearch']);?>", {goodsId: goodsId}, function (data) {
                if(data.state == 'ok') {

                    var htmlStr = '<tr id="tr_id_'+data.result.goodsId+'">';
                    htmlStr += '<td><input type="hidden" name="goodsId[]" value="'+data.result.goodsId+'">'+data.result.goodsNumber+'</td>';
                    htmlStr += '<td>'+data.result.goodsName+'</td>';
                    htmlStr += '<td>'+data.result.goodsSpec+'</td>';
                    htmlStr += '<td>'+data.result.unitName+'</td>';
                    htmlStr += '<td><input type="text" min="0" oninput="insertGoodsPrice('+data.result.goodsId+');" id="sales_goods_price_'+data.result.goodsId+'" name="salesGoodsPrice[]" class="form-control" value="'+erpNumber(data.result.goodsRecommendPrice, 2)+'"></td>';
                    htmlStr += '<td><input type="number" min="1" oninput="insertGoodsPrice('+data.result.goodsId+');" id="sales_goods_sell_num_'+data.result.goodsId+'" name="salesGoodsSellNum[]" class="form-control col-sm-6" value="1"></td>';
                    htmlStr += '<td><input type="text" min="0" oninput="insertGoodsPrice('+data.result.goodsId+');" id="sales_goods_tax_'+data.result.goodsId+'" name="salesGoodsTax[]" class="form-control" value="0"></td>';
                    htmlStr += '<td><input type="text" oninput="sumAmount();" id="sales_goods_amount_'+data.result.goodsId+'" name="salesGoodsAmount[]" class="form-control" value="'+erpNumber(data.result.goodsRecommendPrice, 2)+'"></td>';
                    htmlStr += '<td><button type="button" onclick="deleteGoods('+data.result.goodsId+');" class="btn btn-danger"><?= $this->translate('删除')?></button></td>';
                    htmlStr += '</tr>';

                    $('#tr-end').before(htmlStr);

                    $('#goodsSearch').val('');
                    $('#selectedGoodsId').val('');
                    sumAmount();
                }
            })
        }
    }

    function insertGoodsPrice(id) {
        var goodsPrice  = $('#sales_goods_price_'+id).val();
            goodsPrice  = goodsPrice == '' ? 0 : parseFloat(goodsPrice);
        var goodsTax  = $('#sales_goods_tax_'+id).val();
            goodsTax  = goodsTax == '' ? 0 : parseFloat(goodsTax);
        var goodsNum    = $('#sales_goods_sell_num_'+id).val();
            goodsNum    = goodsNum == '' ? 1 : parseInt(goodsNum);

        var goodsAmount = goodsPrice * goodsNum + goodsTax;

        $('#sales_goods_amount_'+id).val(erpNumber(goodsAmount, 2));

        sumAmount();
    }

    function sumAmount() {
        var orderAmount = 0;
        $("input[name='salesGoodsAmount[]']").each(function () {
            orderAmount = orderAmount + parseFloat($(this).val());
        });
        $('#order-amount').html(erpNumber(orderAmount, 2));
    }

    function deleteGoods(goodsId) {
        <?php if(isset($salesOrderInfo)) { ?>
        $.post("<?= $this->url('sales-order', ['action' => 'delSalesOrderGoods']);?>", {orderId: <?=$salesOrderInfo->getSalesOrderId()?>, goodsId: goodsId}, function (data) {
            if(data.state != 'ok') {
                layer.msg('<?= $this->translate('商品删除失败！')?>');
            } else {
                $('#tr_id_'+goodsId).remove();
                sumAmount();
            }
        });
        <?php } else { ?>
        $('#tr_id_'+goodsId).remove();
        sumAmount();
        <?php } ?>
    }

    function addMoreGoods() {
        $('#modalDefault').modal('show');
        dberpAjaxList('<?= $this->url('goods', ['action' => 'ajaxGoodsSearch']);?>', 'addGoodsListBody');
    }

    function addMoreSelectGoods() {
        $("input[name='selectGoodsId[]']").each(function () {
            if(this.checked) {
                addSelectGoods(this.value);
            }
        });
        $('#modalDefault').modal('hide');
    }

    function searchGoods() {
        dberpAjaxList('<?= $this->url('goods', ['action' => 'ajaxGoodsSearch']);?>?searchGoodsName='+$('#searchGoodsName').val(), 'addGoodsListBody');
    }
</script>