<!DOCTYPE html>
<!--[if IE 8]>
<html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]>
<html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html>
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
    <base href="#springUrl('/assets/adminlte/')"/>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>工作台</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <!-- Bootstrap 3.3.5 -->
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="plugins/font-awesome/css/font-awesome.min.css">
    <!-- Ionicons -->
    <link rel="stylesheet" href="plugins/ionicons/css/ionicons.min.css">

    <!-- DataTables -->
    <link rel="stylesheet" href="plugins/datatables/dataTables.bootstrap.css">

    <link rel="stylesheet" href="plugins/select2/select2.min.css">

    <!-- Theme style -->
    <link rel="stylesheet" href="dist/css/AdminLTE.min.css">
    <!-- AdminLTE Skins. Choose a skin from the css/skins
         folder instead of downloading all of them to reduce the load. -->
    <link rel="stylesheet" href="dist/css/skins/_all-skins.min.css">
    <!-- iCheck -->
    <link rel="stylesheet" href="plugins/iCheck/flat/blue.css">
    <!-- Date Picker -->
    <link rel="stylesheet" href="plugins/datepicker/datepicker3.css">
    <!-- Daterange picker -->
    <link rel="stylesheet" href="plugins/daterangepicker/daterangepicker-bs3.css">
    <!-- bootstrap wysihtml5 - text editor -->
    <link rel="stylesheet" href="plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
    <!--validate css-->
    <link rel="stylesheet" href="plugins/jquery-validation/css/validate.css">
    <!--fileinput css-->
    <link rel="stylesheet" href="plugins/bootstrap-fileinput/bootstrap-fileinput.css">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<!-- END HEAD -->
<body class="hold-transition skin-blue sidebar-mini">

<div class="wrapper">
    <div class="content-wrapper" style="margin-left:0;">

        <section class="content-header">
            <h1>
                需求清单管理
                <small>需求清单管理</small>
            </h1>
            <ol class="breadcrumb">
                <li><a href="#"><i class="fa fa-dashboard"></i>首页</a></li>
                <li><a class="active">需求清单管理</a></li>
            </ol>
        </section>


        <!-- Main content -->
        <section class="content">
            <div class="row">
                <div class="col-xs-12">
                    <!-- general form elements disabled -->
                    <div class="box box-primary">
                        <!--<form role="form" id="myForm">-->
                            <input id="id" name="id" value="$!{data.id}" hidden="true"/>
                            <div class="box-body">

                                <div class="panel panel-primary">
                                    <div class="panel-heading">订单信息</div>

                                    <div class="panel-body">
                                        <div class="form-group form-md-line-input col-xs-5">
                                            <label>订单编码<font style="color: red"></font></label>
                                            <input type="text"
                                                   class="form-control" name="orderCode"
                                                   id="number" readonly="readonly"
                                                   maxlength="50" placeholder="订单编码"
                                                   value="$!{data.number}">
                                        </div>

                                        <div class="form-group form-md-line-input col-xs-5">
                                            <label>快递单号<font style="color: red"></font></label>
                                            <input type="text"
                                                   class="form-control" name="courierNumber"
                                                   id="courierNumber" readonly="readonly"
                                                   maxlength="50" placeholder="快递单号"
                                                   value="$!{data.courierNumber}" >
                                        </div>

                                        <div class="form-group form-md-line-input col-xs-5">
                                            <label>订单总价<font style="color: red"></font></label>
                                            <input type="text"
                                                   class="form-control" name="orderAmount"
                                                   id="orderAmount" readonly="readonly"
                                                   maxlength="50" placeholder="订单金额"
                                                   value="$!{data.orderAmount}"
                                            >
                                        </div>

                                        <div class="form-group form-md-line-input col-xs-5">
                                            <label>收货地址<font style="color: red"></font></label>
                                            <input type="text"
                                                   class="form-control" name="address"
                                                   id="address" readonly="readonly"
                                                   maxlength="50" placeholder="收货地址"
                                                   value="$!{data.address}"
                                            >
                                        </div>
                                        <div class="form-group form-md-line-input col-xs-5">
                                            <label>订单状态<font style="color: red"></font></label>
                                            <input type="text"
                                                   class="form-control" name="payStatus"
                                                   id="payStatus" readonly="readonly"
                                                   maxlength="50" placeholder=""
                                                   value="$!{data.payStatus}"
                                            >
                                        </div>
                                        <div class="form-group form-md-line-input col-xs-5">
                                            <label>支付备注<font style="color: red"></font></label>
                                            <input type="text"
                                                   class="form-control" name="description"
                                                   id="description" readonly="readonly"
                                                   maxlength="50" placeholder=""
                                                   value="$!{data.description}"
                                            >
                                        </div>
                                        <div class="form-group form-md-line-input col-xs-5">
                                            <label>支付交易号<font style="color: red"></font></label>
                                            <input type="text"
                                                   class="form-control" name="tradeNo"
                                                   id="tradeNo" readonly="readonly"
                                                   maxlength="50" placeholder=""
                                                   value="$!{data.tradeNo}"
                                            >
                                        </div>

                                        <div class="form-group form-md-line-input col-xs-5">
                                            <label>创建时间<font style="color: red"></font></label>
                                            <input type="text"
                                                   class="form-control" name="createTime"
                                                   id="createTime" readonly="readonly"
                                                   maxlength="50" placeholder=""
                                                   value="$!{data.createTime}"
                                            >

                                        </div>

                                        <div class="form-group form-md-line-input col-xs-8">
                                            <label>订单取消原因<font style="color: red"></font></label>
                                            <textarea class="form-control" id="orderCancel" name="orderCancel" rows="3" readonly>$!{data.orderCancel}</textarea>
                                        </div>


                                    </div>
                                </div>

                                <div class="panel panel-primary">
                                    <div class="panel-heading">商品信息</div>
                                    <div class="panel-body">
                                        <div class="form-group form-md-line-input">
                                            <div id="group" class="list-group">
                                                <li class="list-group-item">
                                                    <th style=""><label style="width: 180px;margin-right: 50px;text-align: center">商品名称</label></th>
                                                    <th style=""><label style="width: 160px;margin-right: 50px;text-align: center">商品编码</label></th>
                                                    <th style=""><label style="width: 180px;margin-right: 50px;text-align: center">购买数量</label></th>
                                                    <th style=""><label style="width: 180px;margin-right: 50px;text-align: center">出货数量</label></th>
                                                </li>


                                            </div>

                                            <div class="form-group form-md-line-input col-xs-8">
                                                <label>已扫商品编码<font></font></label>
                                                <textarea class="form-control" id="scanGoodsCode" name="scanGoodsCode" rows="5" readonly></textarea>
                                            </div>
                                            <!--<button type="button" class="search btn btn-primary" onclick="clickAdd()">添加商品和数量</button>-->
                                        </div>
                                    </div>
                                </div>

                                <div class="box-footer">
                                    #if($shiro.hasPermission("qy:order:edit"))
                                    <button class="btn btn-primary" onclick="save()">保存</button>
                                    #end
                                    <a href="#springUrl('/a/order/list')" class="btn btn-default">取消</a>
                                </div>
                        <!--</form>-->
                        <!-- /.box-body -->
                    </div><!-- /.box -->
                    </div>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </section><!-- /.content -->
    </div><!-- /.content-wrapper -->


    <!-- Add the sidebar's background. This div must be placed
         immediately after the control sidebar -->
    <div class="control-sidebar-bg"></div>
</div><!-- ./wrapper -->

<script src="plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="bootstrap/js/bootstrap.min.js"></script>

<script src="plugins/select2/select2.full.min.js"></script>
<!-- DataTables -->
<script src="plugins/datatables/jquery.dataTables.min.js"></script>
<script src="plugins/datatables/extensions/i18n/lanauage_ch.js"></script>
<script src="plugins/datatables/dataTables.bootstrap.min.js"></script>
<!-- SlimScroll -->
<script src="plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="plugins/fastclick/fastclick.min.js"></script>
<!--fileinput js-->
<script src="plugins/bootstrap-fileinput/bootstrap-fileinput.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/app.min.js"></script>
<script src="plugins/bootstrap-maxlength/bootstrap-maxlength.min.js" type="text/javascript"></script>
<script src="plugins/security/sha256.js" type="text/javascript"></script>
<script src="plugins/jquery-validation/js/jquery.validate.min.js"></script>
<script src="js/jquery.form.min.js"></script>
<script type="text/javascript" charset="utf-8" src="plugins/ueditor-min-1.4.3/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="plugins/ueditor-min-1.4.3/ueditor.all.js"></script>
<script type="text/javascript" charset="utf-8" src="plugins/ueditor-min-1.4.3/lang/zh-cn/zh-cn.js"></script>
<script src="common/js/cfapp.js"></script>
<!-- END PAGE LEVEL PLUGINS -->
<script>
    var csrf='${_csrf.token}';
    var csrf_header='${_csrf.headerName}';
    var areaList = [];


    //扫码全局变量
    var scanCodeStr = "";
    var scanSubCode = "";
    var avgTime = 30;
    var lastTime = 0;

    //触发顺序keydown keypress keyup
    $(document).on('keydown', function(event){
        let subCode = String.fromCharCode(event.keyCode);

        let currTime = new Date().getTime();
        let spaceTime = currTime - lastTime;
        //扫码间隔大于30，未认为输入

        if (lastTime != 0 && spaceTime > avgTime) {
            return;
        }

        if (event.keyCode == 13) {
            lastTime = 0;

            let nextEleV = 0;
            let scanNumEle = null;
            let flag = false;
            $("#group").find('input[name="productCode"]').each(function() {
                if ($(this).val() == scanSubCode) {
                    nextEleV = $(this).next().val();
                    scanNumEle = $(this).next().next();
                    flag = true;
                }
            });
            if (!flag) {
                Cfapp.alert({
                    message: "商品未在订单中!",
                    btntext: "确定",
                    success: function () {}
                });
                scanSubCode = "";
                return;
            }

            scanCodeStr += scanSubCode + "|";
            let count = 0;
            if (scanCodeStr != "" && scanCodeStr != null) {
                let arr = scanCodeStr.split("|");
                console.log(arr.length);
                for(let i=0; i<arr.length; i++) {
                    if (arr[i] == scanSubCode)
                        count++;
                }
                if (nextEleV < count) {
                    Cfapp.alert({
                        message: "商品超过订单数量!",
                        btntext: "确定",
                        success: function () {}
                    });
                    scanSubCode = "";
                    return;
                }

            }


            scanNumEle.val(count);
            $('textarea[name="scanGoodsCode"]').text(scanCodeStr);

            scanSubCode = "";
            return;
        }

        scanSubCode += subCode;
        lastTime = currTime;
    });

//    $(document).on('keypress', function(event){
//        if(event.keyCode == 13){
//            //alert('你按下了Enter' + 2);
//        }
//    });
//
//    $(document).on('keyup', function(event){
//        if(event.keyCode == 13){
//            //alert('你按下了Enter' + 3);
//        }
//    });

    function checkProductCode(code) {
        let flag = true;
        $("#group").find('input[name="productCode"]').each(function(e) {
            if (e.val() == code) {
                let count = e.next().val();
                let length = $('textarea[name="scanGoodsCode"]').text().split(code).length - 1;
                if (count >= length)
                    return true;
            }
        });
        if (!flag) {
            return flag;
        }
    }

    function list() {
        var url = "#springUrl('/a/order/fromProduct')"
        $.ajax({
            url: url,
            type: "GET",
            success: function (data) {
                areaList = JSON.parse(data.data);
                // var province = document.querySelector('#selectProduct')
                // for (index in areaList) {
                //     var op = new Option(areaList[index].productName, areaList[index].id, false, false)
                //     province.options[province.length] = op
                // }
                var provinceId = '$!{data.productId}';
                var selectProductList = '$!{list}';
                if (selectProductList != null && selectProductList != '') {
                    selectProductList = JSON.parse(selectProductList);
                    for (var i = 0; i < selectProductList.length; i++) {
                        var obj = selectProductList[i];
                        // if($(this).val() == obj.provinceId){
                        //     $(this).attr('selected', 'selected');
                        // }
                        clickAdd(obj.id, obj.productId, obj.productName, obj.drugsNum, obj.price, obj.amount, obj.productNumber);
                    }
                }
                // $('#selectProduct option').each(function () {
                //     for(var index= 0;i<selectProductList.length;i++){
                //         var obj = selectProductList[i];
                //         if($(this).val() == obj.provinceId){
                //             $(this).attr('selected', 'selected');
                //         }
                //     }
                //
                // })
            }
        });
    }

    $().ready(function () {
        $("#divClass").css('display', 'none')
        var payStatus = $("#payStatus").val();
        if (payStatus == '0') {
            $("#payStatus").val("未付款");
        } else if (payStatus == '1') {
            $("#payStatus").val("已付款");
        } else if (payStatus == '2') {
            $("#payStatus").val("已取消");
        } else {
            $("#payStatus").val("");
        }


        var confirm = $("#confirm").val();
        if (confirm = '0') {
            $("#divClass").css('display', 'blocks')
        }

        Cfapp.init();

        list();


        // var selectdrugsNum  = $("#selectdrugsNum");
        // for (var i = 1; i <=30; i ++){
        //     selectdrugsNum.append("<option value='"+[i]+"'>"+[i]+"</option>")
        // }
        // var  drugsNum = "$!{data.drugsNum}";
        // $('#selectdrugsNum option').each(function () {
        //     if($(this).val() == drugsNum){
        //         $(this).attr('selected', 'selected');
        //     }
        // })


    });


    function clickAdd(id, productId, productName, count, price, amount, number) {
        var options = "";
        if (productName && productName != null) {
            options = `<input  name="productName" class="form-control" style="width: 180px ;margin-right: 50px" type='text' readonly="readonly"  value="`+productName+`"></input>`;
        }

        var idHtml = "";
        if (id && id != null){
            idHtml +=`<input type="hidden" name="idDetail" value="${id}">`
        }else{
            idHtml +=`<input type="hidden" name="idDetail" value="">`
        }

        var htmlNumber = "";
        if (number && number != null) {
            htmlNumber += `<input  name="productCode" class="form-control" style="width: 180px ;margin-right: 50px" type='text' readonly="readonly"  value="`+number+`"></input>`;
        }

        var listHtml = "";
        if (count && count != null) {
            price
            listHtml += `<input name="orderNum" class="form-control" type="text" style="width: 180px;margin-right: 50px;" readonly value=${count} ></input>`;
        } else {
            listHtml += `<input name="orderNum" class="form-control" type="text" style="width: 180px ;margin-right: 50px;" readonly value="1"></input>`;
        }



        var HtmlAmount = `<input name="sendNum" class="form-control" type="text" style="width: 180px ;margin-right: 50px;" readonly value="0"></input>`;

        //扫码商品编码
        var HtmlCode = `<button name="delGoods" type="button" class="btn btn-danger">删除</button>`;


        let html = `<li id="form-translate" class="list-group-item"  style="display:flex;">
                        ${idHtml}

                        ${options}

                        ${htmlNumber}

                        ${listHtml}

                        ${HtmlAmount}

                        ${HtmlCode}
                    </li>`;

        $("#group").append(html);
        toTal()
    }

    function  toTal() {
//        $('#group').on('click', '.scanGoods', function() {
//            $(this).prev().val("11111111111");
//        });

        var count = 0
        $('.group [name="htmlAmount"]').each(function(index, item){
            count += +item.value
        })
        $("#orderAmount").val(count.toFixed(2));
    }

    /**
     * 保存事件
     */
    function save() {
        var arr = []
        var obj = {}

        $('.translate').each((index, item) => {
            var txt = $(item).find('[name="releas"]').val()

            if (obj[txt]) {
                arr.push(index)
                return
            } else {
                obj[txt] = true
            }
        })
        if (arr.length > 0) {
            Cfapp.alert({
                message: "无法增加重复商品!",
                btntext: "确定",
                success: function () {
                }
            });
            return;
        }
            var  id = $("#id").val()
         var orderAmount = $("#orderAmount").val()
        var datas = [];
        $('.translate').each(function (index,item){
            const idDetail = $(item).find('[name="idDetail"]').val()
            const productId = $(item).find('[name="releas"]').val()
            const drugsNum = $(item).find('[name="listHtml"]').val()
            const price = $(item).find('[name="htmlPrice"]').val()
            const amount = $(item).find('[name="htmlAmount"]').val()
            datas.push({
                id : id,
                idDetail : idDetail,
                productId :productId,
                drugsNum : drugsNum,
                price : price,
                amount : amount,
                orderAmount :orderAmount
            })
        })

        var url = "#springUrl('/a/order/formData')"

        $.ajax({
            url: url,
            type: "POST",
            dateType:'json',
            headers:{"Accept": "application/json;charset=UTF-8"},
            data : {_csrf:csrf,_csrf_header:csrf_header,datas:JSON.stringify(datas)},
            success :function (rsp) {
               if(rsp.errorNo == "0"){
                   Cfapp.alert({
                       message: "修改成功",
                       btntext: "确定",
                       success: function () {
                           location.href = "#springUrl('/a/order/list')";
                       }
                   });
               }else{
                   Cfapp.alert({
                        message: "修改失败",
                        btntext: "确定",
                        success: function () {
                            let idTmp = $('input[name="id"]').val();
                            location.href = "#springUrl('/a/order/form?id="+idTmp+"')";
                        }
                   });
               }
            }

        });
    }

     var recdTypeAdd = function () {
         var initForm = function () {
             var initFormCtrl = function () {
                 bindEvent();
             };
             var bindEvent = function () {
                $('.scanCode').focus();
             };
             initFormCtrl();
         };
         return {

             //main function to initiate the module
             init: function () {
                 initForm();
             }

         };
     }();
</script>
</body>
<!-- END BODY -->
</html>