<!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 class="form-group form-md-line-input col-xs-5">
                                            <label>是否三期用户<font style="color: red"></font></label>
                                            <input type="text"
                                                   class="form-control" name="isThree"
                                                   id="isThree" readonly="readonly"
                                                   maxlength="50" placeholder=""
                                                   value="$!{isThree}"
                                            >
                                        </div>

                                        <div class="form-group form-md-line-input col-xs-10">
                                            <label>付款链接<font style="color: red"></font></label>
                                            <input type="text"
                                                   class="form-control" name="payUrl"
                                                   id="payUrl" readonly="readonly"
                                                   maxlength="50" placeholder=""
                                                   value="$!{data.payUrl}"
                                            >
                                        </div>

                                        <div class="form-group form-md-line-input col-xs-10">
                                            <label>付款二维码<font style="color: red"></font></label>
                                            <div id="qrcodeDiv"></div>
                                        </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>
                                            #if ($!{isView} != 'true')
                                            <button type="button" class="search btn btn-primary" onclick="clickAdd()">添加商品</button>
                                            #end
                                        </div>
                                    </div>
                                </div>

                                <div class="box-footer">
                                    #if ($!{isView} != 'true')
                                    #if($shiro.hasPermission("qy:order:edit"))
                                    <button class="btn btn-primary" onclick="save()">保存</button>
                                    #end
                                    #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 type="text/javascript"
        src="plugins/qrcode/qrcode.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 = [];
    var isView = `$!{isView}`;

    let isThree = `$!{isThree}`;
    if (isThree != null && isThree != '') {
        $('input[name="isThree"]').val(isThree == '0' ? '是' : '否');
    }

    let status = `$!{data.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 '5':
                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);
                if (isView == "true") {//查看
                    let details = `$!{list}`;
                    console.log(details);
                    if (details != null && details != '' && details != '[]') {
                        let arr = JSON.parse(details);
                        for (let i = 0; i < arr.length; i ++) {
                            let obj = arr[i];
                            clickAdd(obj.id, obj.productId, obj.drugsNum, 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.drugsNum, 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;" #if($!{isView}  == 'true') readonly="readonly" #end 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) {
            HtmlPrice += `<input name="htmlPrice" class="form-control" data-price="`+price+`" style="width: 180px ;margin-right: 50px" type='text' `;
            if (bool == "1" || isView == "true") { 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" `;
            if (bool == "1" || isView == "true") { HtmlPrice += `readonly="readonly"`; }
            HtmlPrice += ` onchange="updatePrice(this)" value="`+priceTmp+`"></input>`;
        }

        var HtmlAmount = "";
        if (amount != null) {
            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 htmlDel = "";
        if (isView != 'true') {
            htmlDel += `<button type="button" class="search btn btn-primary" style="background-color: #d73925 ;" onclick="deleteSelect(event)">删除</button>`;
        }
        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;" #if($!{isView} == 'true') disabled="disabled" #end onchange="getPrice(this)">
                            ${options}
                        </select>
                            ${listHtml}

                            ${HtmlPrice}

                            ${HtmlAmount}

                            ${htmlDel}
                    </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+"')";
                        }
                   });
               }
            }

        });
    }

    let qrcodeUrl = `$!{data.payUrl}`;
    var qrcode = new QRCode("qrcodeDiv",
        {
        render: "canvas", //也可以替换为table
        width: 200,
        height: 200,
        text: qrcodeUrl
    });
</script>
</body>
<!-- END BODY -->
</html>