<!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}"-->
                                            <!--&gt;-->
                                        <!--</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="status"
                                                   id="status" readonly="readonly"
                                                   maxlength="50" placeholder=""
                                                   value="$!{data.status}"
                                            >
                                        </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}"-->
                                            <!--&gt;-->
                                        <!--</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: 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>
                                                </li>
                                            </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 goodsList = [];

    let status = `$!{data.status}`;
    console.log(status);
    if (status != null && status != '') {
        let str = "";
        switch (status) {
            case '0':
                str = "待确认";
                break;
            case '1':
                str = "待付款";
                break;
            case '2':
                str = "代发货";
                break;
            case '3':
                str = "待收货";
                break;
            case '4':
                str = "已完成";
                break;
            case '4':
                str = "已取消";
                break;
        }
        $('input[name="status"]').val(str);
    }

    goodList();
    function goodList() {
        var url = "#springUrl('/a/order/fromProduct')"
        $.ajax({
            url: url,
            type: "GET",
            success: function (res) {
                goodsList = JSON.parse(res.data);
                //订单产品
                let detailList  = `$!{list}`;
                if (detailList != null && detailList != '' && detailList != '[]') {
                    let arr = JSON.parse(detailList);
                    for (let i = 0; i < arr.length; i ++) {
                        let obj = arr[i];
                        clickAdd(obj.id, obj.productId, obj.count, obj.price, obj.amount);
                    }
                } else {
                    let datas = `$!{data.description}`;
                    if (datas != null && datas != "") {
                        let arr = JSON.parse(datas);
                        for (let i = 0; i < arr.length; i ++) {
                            let obj = arr[i];
                            clickAdd(null, obj.productId, obj.count, obj.price, obj.amount);
                        }
                    }
                }


            }
        });
    }

    function clickAdd(id, productId, count, price, amount) {
        var options = goodsList.map(function (item) {
            if (productId && productId != null && item.id === productId) {
                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('');

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

        var listHtml = "";
        if (count && count != null) {
            listHtml += `<input name="listHtml" class="form-control" type='number' style="width: 180px;margin-right: 50px; margin-left: 50px;" 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" class="form-control" type='number' style="width: 180px ;margin-right: 50px; margin-left: 50px;" 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>`;
        }

        let bool = `$!{isThree}`;
        var HtmlPrice = "";
        if (price != null && price != '') {
            HtmlPrice += `<input name="htmlPrice" class="form-control" data-price="`+price+`" style="width: 180px ;margin-right: 50px" type='text' `;
            if (bool == "1") { HtmlPrice += `readonly="readonly"`; }
            let priceTmp = parseInt(price).toFixed(2);
            HtmlPrice +=` onchange="updatePrice(this)" value="`+priceTmp+`"></input>`;
        } else {
            let priceTmp = parseInt(goodsList[0].price).toFixed(2);
            HtmlPrice += `<input name="htmlPrice" class="form-control" data-price="`+priceTmp+`" style="width: 180px ;margin-right: 50px" type="text" `;
            //console.log(bool);
            if (bool == "1") { HtmlPrice += `readonly="readonly"`; }
            HtmlPrice += ` onchange="updatePrice(this)" value="`+priceTmp+`"></input>`;
        }

        var HtmlAmount = "";
        if (amount != null && amount != '') {
            HtmlAmount += `<input id="htmlAmount" class="form-control" name="htmlAmount" style="width: 180px ;margin-right: 50px" type='text' readonly="readonly"   value="`+parseInt(amount).toFixed(2)+`" ></input>`;
        } else {
            var amountTmp = parseInt(goodsList[0].price).toFixed(2);
            HtmlAmount += `<input id="htmlAmount" class="form-control" name="htmlAmount" style="width: 180px;margin-right: 50px" type="number" readonly="readonly"  value="`+amountTmp+`"></input>`
        }


        let html = `<li id="form-translate" class="list-group-item translate"   style="display:flex ;">
                            ${idHtml}
                        <select  class="form-control select2 releas" name="releas" style="width: 180px;"  onchange="getPrice(this)">
                            ${options}
                        </select>
                            ${listHtml}

                            ${HtmlPrice}

                            ${HtmlAmount}
                        <button type="button" class="search btn btn-primary" style="background-color: #d73925 ;" onclick="deleteSelect(event)">删除</button>
                    </li>`;

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

    function initSelect2() {
        $('.releas').select2({
            placeholder: '选择商品'
        });
    }

    function getPrice(e) {
        let price = $(e).find("option:selected").attr('data-price');
        $(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);
    }

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

    function updatePrice(value) {
        var price = $(value).val();
        var number = $(value).parent().find('input[name="listHtml"]').val();
        var amount = (price * number).toFixed(2);
        $(value).parent().find('input[name="htmlAmount"]').val(amount);
        toTal();
    }

    function deleteSelect(event) {
        var dom = event.target;
        var ret = $(dom);
        ret.parent().remove();
        toTal();
    }

    /**
     * 计算商品总价
     */
    function toTal() {
        var amount = 0;
        $('.translate [name="htmlAmount"]').each(function(index, item){
            amount += +item.value
        })
        $("#orderAmount").val(amount.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()
            console.log(item)
            datas.push({
                id : id,
                idDetail : idDetail,
                productId :productId,
                drugsNum : drugsNum,
                price : price,
                amount : amount,
                orderAmount :orderAmount
            })
        })
        if (!datas[0].productId){
            Cfapp.alert({
                message: "订单至少包含一件商品",
                btntext: "确定",
                success: function () {
                    location.href = "#springUrl('/a/order/list')";
                }
            });
            return;
        }

        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) {
                console.log(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 () {
    //
    //             $("#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>