<!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">

    <!-- 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="form-group form-md-line-input">
                                    <label>订单编码<font style="color: red"></font></label>
                                    <input type="text"
                                           class="form-control" name="orderCode"
                                           id="orderCode" readonly="readonly"
                                           maxlength="50" placeholder="订单编码"
                                           value="$!{data.orderCode}"
                                    >
                                    <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}"
                                    >
                                    <label>商品编码<font style="color: red"></font></label>
                                    <input type="text"
                                           class="form-control" name="productNumber"
                                           id="productNumber" readonly="readonly"
                                           maxlength="50" placeholder="商品编码"
                                           value="$!{data.productNumber}"
                                    >
                                    <br/>


                                    <div id="group" class="group">


                                            <th style="width:15%; "><label
                                                    style="width: 180px;margin-right: 80px;text-align: center">商品名称</label></th>
                                            <th style=""><label style="width: 180px;margin-right: 80px;text-align: center">商品购买数量</label>
                                            </th>
                                            <th style=""><label style="width: 160px;margin-right: 80px;text-align: center">商品单价</label></th>
                                            <th style=""><label style="width: 180px;margin-right: 80px;text-align: center">商品总价</label></th>


                                    </div>
                                    <br/>
                                    <button type="button" class="search btn btn-primary" onclick="clickAdd()">添加商品和数量
                                    </button>
                                    <br/><br/>
                                    <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}"
                                    > <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}"
                                    >
                                    <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}"
                                    >
                                    <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}"
                                    >
                                    <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}"
                                    >
                                    <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 id="divClass">
                                        <label>订单取消原因<font style="color: red"></font></label>
                                        <input type="text"
                                               class="form-control" name="orderCancel"
                                               id="orderCancel" readonly="readonly"
                                               maxlength="50" placeholder=""
                                               value="$!{data.orderCancel}"
                                        >
                                    </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>
                                </div>
                        </form>
                        <!-- /.box-body -->
                    </div><!-- /.box -->


                </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>
<!-- 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 = [];

    function list() {
        var url = "#springUrl('/a/order/fromProduct')"
        $.ajax({
            url: url,
            type: "GET",
            success: function (data) {
                console.log(data+"aaaa")
                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.productId, obj.drugsNum, obj.price, obj.amount);
                    }
                }
                // $('#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, count, price, amount) {
        debugger
        var options = areaList.map(function (item) {
            if (id && id != null && item.id === id) {
                return `<option selected value="${item.id}" data-price="${item.price}">${item.productName}</option>`
            } else {
                return `<option value="${item.id}" data-price="${item.price}">${item.productName}</option>`
            }
        }).join('')
        console.log(options);

        var listHtml = "";

        if (count && count != null) {
            price
            listHtml += `<input name="listHtml" type='number' style="width: 180px;margin-right: 80px" oninput="if(value>100)value=100;if(value.length>2)value=value.slice(0,2);if(value<=0)value=1" onchange="updateCount(this)" value=${count} ></input>`;
        } else {
            listHtml += `<input name="listHtml" type='number' style="width: 180px ;margin-right: 80px" oninput="if(value>100)value=100;if(value.length>2)value=value.slice(0,2);if(value<=0)value=1" onchange="updateCount(this)" value="1"></input>`;
        }

        var HtmlPrice = "";
        if (price && price != null) {
            HtmlPrice += `<input  name="htmlPrice" style="width: 180px ;margin-right: 80px" type='text' readonly="readonly"  value="`+price.toFixed(2)+`"></input>`;
        } else {
            // var item = areaList.find(item => item.id === id)
            var item = areaList[0]
            priveTmp = item.price.toFixed(2)
            HtmlPrice += `<input   name="htmlPrice" data-price="${item.id}" style="width: 180px ;margin-right: 80px" type="text"  readonly="readonly" value="${priveTmp}"></input>`
        }
        var HtmlAmount = "";

        if (amount && amount != null) {
            // var amout = ${amount};
            HtmlAmount += `<input id="htmlAmount" name="htmlAmount" style="width: 180px ;margin-right: 80px" type='text' readonly="readonly"   value="`+amount .toFixed(2)+`" ></input>`;
        } else {
            // var item = areaList.find(item => item.id === id)
            var countSi = 1;
            var amountPrice = countSi * item.price
            var amountTmp = amountPrice.toFixed(2)
            var item = areaList[0]
            HtmlAmount += `<input id="htmlAmount" name="htmlAmount"  data-price="${item.id}" style="width: 180px ;margin-right: 80px" type="text"  readonly="readonly"  value="${amountTmp}"></input>`
        }


        let html = `<div id="form-translate" class="translate" style="display: flex ;margin-bottom: 30px">
                            <select  class="form-control" name="releas" style="width: 180px ;margin-right: 80px"  onchange="getPrice(this)">
                                  ${options}
                            </select>

                                     ${listHtml}

                                     ${HtmlPrice}

                                     ${HtmlAmount}

                                    <button type="button" class="search btn btn-primary" style="background-color: #d73925 ;margin-left: 200px" onclick="deleteSelect(event)">删除
                                    </button>
                                 </div>`

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

    function getPrice(e) {
        let price = $(e).find("option:selected").attr('data-price');
        //let price = $(e).parent().find('input[name="htmlPrice"]').attr("target-data");
        $(e).parent().find('input[name="htmlPrice"]').val(price);
        let value = $(e).parent().find('input[name="htmlPrice"]').val()
        let count = $(e).parent().find('input[name="listHtml"]').val()
        let val = value * count;
        $(e).parent().find('input[name="htmlAmount"]').val(val)
        // let  htmlAmount = $(e).parent().find('input[name="htmlAmount"]').val()
        toTal()
    }



    function updateCount(value) {
        var price = $(value).parent().find('input[name="htmlPrice"]').val()
        var valueSi = $(value).val()
        var totalPrice = valueSi * price;
        $(value).parent().find('input[name="htmlAmount"]').val(totalPrice)
        toTal()
    }

    function updatePrice(e) {
        // var orderAmount = $("#orderAmount");
        var valueSi = $(value).val();
        console.log('lsss',valueSi)
     // var sign = Math.floor(valueSi * 100 ) /100
          $("#orderAmount").val(valueSi.toFixed(2));

    }
    function deleteSelect(event) {
        var dom = event.target;
        var ret = $(dom);
        console.log(ret.parent()+"ssss")
        ret.parent().remove();
        toTal()
    }
    
    function  toTal() {
        var count = 0
        $('.group [name="htmlAmount"]').each(function(index, item){
            count += +item.value
        })
        $("#orderAmount").val(count.toFixed(2));
    }
    function save() {
        $('.translate').each(function (index,item) {
            const productId = $(item).find('[name="releas"]').val()
           if($('.translate').find('[name="releas"]')[index].value==$('.translate').find('[name="releas"]')[index+1].value){
               alert('商品名称不能重复')
           }
        })

            var  id = $("#id").val()
         var orderAmount = $("#orderAmount").val()
        var datas = [];
        $('.translate').each(function (index,item){
            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()
            console.log(item)
            datas.push({
                id : id,
                productId :productId,
                drugsNum : drugsNum,
                price : price,
                amount : amount,
                orderAmount :orderAmount
            })
        })

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

        $.ajax({
            url: url,
            type: "POST",

            data : {_csrf:csrf,_csrf_header:csrf_header,"datas":JSON.stringify(datas)},
            success :function (rsp) {
               if(rsp.aaData == 1){
                   Cfapp.alert({
                       message: "修改成功",
                       btntext: "确定",
                       success: function () {
                           location.href = "#springUrl('/a/order/list')";
                       }
                   });
               }else{
                   Cfapp.alert({
                       message: "修改失败",
                       btntext: "确定",
                       success: function () {
                           location.href = "#springUrl('/a/order/from')";
                       }
                   });
               }
            }

        })
    }

    // var recdTypeAdd = function () {
    //     var initForm = function () {
    //         var initFormCtrl = function () {
    //             bindEvent();
    //         };
    //         var bindEvent = function () {
    //
    //             $("#myForm").validate({
    //                 rules: {},
    //                 messages: {},
    //                 submitHandler: function (form) {
    //                     $("#save").attr("disabled", true);
    //                     $.getJSON("#springUrl('/a/order/formData')", $("#myForm").serialize(), function (returnobj) {
    //                         $("#save").attr("disabled", false);
    //                         if (returnobj.errorNo == 2) {  //保存成功
    //                             Cfapp.confirm({
    //                                 message: "添加成功",
    //                                 btnoktext: "继续添加",
    //                                 btncanceltext: "关闭",
    //                                 success: function () {
    //                                     location.href = "#springUrl('/a/order/form')";
    //                                 },
    //                                 cancel: function () {
    //                                     location.href = "#springUrl('/a/order/list')";
    //                                 }
    //                             });
    //                         } else if (returnobj.errorNo == 0) {  //修改成功
    //                             Cfapp.alert({
    //                                 message: "更新成功",
    //                                 btntext: "确定",
    //                                 success: function () {
    //                                     location.href = "#springUrl('/a/order/list')";
    //                                 }
    //                             });
    //                         } else {
    //                             Cfapp.alert({
    //                                 message: "创建失败",
    //                                 btntext: "确定",
    //                                 success: function () {
    //                                     location.href = "#springUrl('/a/order/list')";
    //                                 }
    //                             });
    //                         }
    //                     });
    //                 }
    //             })
    //         }
    //         initFormCtrl();
    //     }
    //     return {
    //
    //         //main function to initiate the module
    //         init: function () {
    //             initForm();
    //         }
    //
    //     };
    // }();
</script>
</body>
<!-- END BODY -->
</html>