{{ define "kas/order_main.htm" }}
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <title>订单管理 - 后台管理 - 看丽人</title>
    <script type="text/javascript">
        const ISGOKEEP = true;
    </script>
    {{ template "_common.htm" .}}
    <script src="{{.global.host_img}}/assets/js/jsrender.min.js"></script>
    <script type="text/javascript" src="{{.global.host_img}}/assets/js/moment.min.js"></script>
    <script type="text/javascript" src="{{.global.host_img}}/assets/js/daterangepicker.min.js"></script>
    <link rel="stylesheet" type="text/css" href="{{.global.host_img}}/assets/css/daterangepicker.css" />
    <script type="text/javascript">
        LoadMemberInfo();
    </script>
</head>

<body>
    {{ template "kas/_header.htm" .}}
    <main role="main">
        <div class="album py-3 bg-light">
            <div class="container">
                {{ template "kas/_nav.htm" .}}
                <div class="alert alert-dark border-bottom"><a href="/kas/order_main">订单管理</a></div>

                <div id="frmSearch">
                    <div class="form-group">
                        <label for="iptOrderCode">订单编号</label>
                        <input name="order_code" type="text" class="form-control" id="iptOrderCode" value=""
                            placeholder="输入订单编号">
                    </div>
                    <div class="form-group">
                        <label for="iptUserid">用户名</label>
                        <input name="userid" type="text" class="form-control" id="iptUserid" value="">
                    </div>
                    <div class="form-group clearfix">
                        <label for="iptTimeRange">时间段</label>
                        <input type="text" id="iptTimeRange" name="time_range"
                            class="form-control pull-right cye-lm-tag">
                    </div>
                    <button id="btnSearch" class="btn btn-danger btn-block" type="submit">搜索</button>
                </div><!-- end frmSearch -->

                <div class="ibox-content table-responsive-sm pt-2">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>订单编号</th>
                                <th>用户ID</th>
                                <th>时间</th>
                                <th>金额</th>
                                <th>状态</th>
                            </tr>
                        </thead>
                        <tbody id="frmResult">
                        </tbody>
                    </table>
                    <nav id="frmPagination" style="display: none">
                        <ul class="pagination justify-content-center">
                            <li class="page-item" id="prePage">
                                <a class="page-link" href="javascript:GoPre()">上一页</a>
                            </li>
                            <li class="page-item disabled" id="totalPage">
                                <a class="page-link"><span id="spCurrentPage">..</span>/<span
                                        id="spTotalPage">..</span>页</a>
                            </li>
                            <li class="page-item" id="nextPage">
                                <a class="page-link" href="javascript:GoNext()">下一页</a>
                            </li>
                        </ul>
                    </nav>
                    <div id="noneResult" style="display: none">
                        <p class='text-center'>暂无记录</p>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <script id="tplOrderRow" type="text/x-jsrender">
  <tr>
    <td>{%:order_code%}</td>
    <td>{%:buyer_id%}</td>
    <td>{%:~unix_to_str(add_at)%}</td>
    <td>{%:price%}</td>
    <td>{%if is_pay%}<font color="green">已支付</font>{%else%}
      <a class="btn btn-sm btn-warning" href="javascript:FinishOrder('{%:order_code%}')">确认收款</a>
    {%/if%}</td>
  </tr>
</script>

    {{ template "kas/_footer.htm" .}}
    <script type="text/javascript">
        var currentpage = 1;
        const pagesize = 20;
        var gokeep_token = GetCookie(TokenName())
        if (gokeep_token == null) {
            DirectTo("/kas");
        }
        $.views.settings.delimiters("{%", "%}"); // 设置js render标签

        // 请求通知权限
        // document.addEventListener('DOMContentLoaded', function () {
        //   if (!Notification) {
        //     alert('Desktop notifications not available in your browser. Try Chromium.'); 
        //     return;
        //   }

        //   if (Notification.permission !== "granted")
        //     Notification.requestPermission();
        // });

        // 通知存在新订单
        // function notifyNewOrder() {
        //   if (Notification.permission !== "granted")
        //     Notification.requestPermission();
        //   else {
        //     var notification = new Notification('看丽人订单通知', {
        //       body: "有新的订单了，请点击查看",
        //     });

        //     notification.onclick = function () {
        //       window.open("/kas/order_main");      
        //     };
        //   }
        // }

        // notifyNewOrder();

        function unix_to_str(time) {
            time = parseInt(time) * 1000;
            var datetime = new Date();
            datetime.setTime(time);
            var year = datetime.getFullYear();
            var month = datetime.getMonth() + 1;
            var date = datetime.getDate();
            var hour = datetime.getHours();
            var minute = datetime.getMinutes();
            return year + "-" + month + "-" + date + " " + hour + ":" + minute;
        }

        $.views.helpers({
            unix_to_str: unix_to_str
        })

        var order_code = "";
        var user_id = "";
        var time_start = moment().startOf('day').unix();
        var time_end = moment().endOf('day').unix();
        var page = currentpage;

        var urlParams = new URLSearchParams(window.location.search);
        if (parseInt(urlParams.get('time_start')) > 0) {
            time_start = parseInt(urlParams.get('time_start'));
        }
        if (parseInt(urlParams.get('time_end')) > 0) {
            time_end = parseInt(urlParams.get('time_end'));
        }
        if (urlParams.get('order_code') != "") {
            order_code = urlParams.get('order_code');
        }
        if (urlParams.get('user_id') != "") {
            user_id = urlParams.get('user_id');
        }
        if (urlParams.get('page') > 0) {
            page = parseInt(urlParams.get('page'));
            currentpage = page;
        }
        if (urlParams.has('page') && urlParams.has('page_size')) {
            GotoPage(page);
        }

        function GoNext() {
            currentpage = currentpage + 1;
            GotoPage(currentpage);
        }

        function GoPre() {
            currentpage = currentpage - 1;
            GotoPage(currentpage);
        }

        // 确认完成订单
        function FinishOrderDo(order_code, modalID) {
            CloseModal("GKModal" + modalID);
            setTimeout(function () {
                $.ajax({
                    url: '/api/v1/auth/order/finish',
                    type: 'GET',
                    dataType: 'json',
                    data: { order_code: order_code },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('Authorization', 'Bearer ' + gokeep_token);
                    },
                })
                    .done(function (data) {
                        Log(data);
                        if (data.code == 0) {
                            if (data.result == true) {
                                PageReload();
                            } else {
                                ShowMsg("确认收款失败");
                            }
                        }
                    })
                    .fail(function () {
                        ShowMsg("确认收款失败");
                    });
            }, 500);

        }

        // 完成订单
        function FinishOrder(order_code) {
            $.ajax({
                url: '/api/v1/auth/order/view',
                type: 'GET',
                dataType: 'json',
                data: { order_code: order_code },
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + gokeep_token);
                },
            })
                .done(function (data) {
                    Log(data);
                    if (data.code == 0) {
                        var footer = "<p><a href='?' class='btn btn-outline-primary' data-dismiss='modal' aria-label='Close'>返回</a> <a href='javascript:FinishOrderDo(\"" + data.result.order.order_code + "\",\"~modalID~\")' class='btn btn-primary'>确认收款</a></p>"
                        var order_info = "<p>订单编号：" + data.result.order.order_code + "</p>";
                        order_info += "<p>创建时间：" + unix_to_str(data.result.order.add_at) + "</p>";
                        order_info += "<p>付费用户：" + data.result.buyer.Userid + "</p>";
                        order_info += "<p>金额：" + data.result.order.price + "元</p>";
                        ShowMsg("<p>是否确定收到当前订单的款项</p>" + order_info, {
                            footer: footer,
                            noClose: true,
                        });
                    }
                })
                .fail(function () {
                    console.log("error");
                });
        }


        $('#iptTimeRange').daterangepicker({
            timePicker: true,
            startDate: moment(time_start * 1000),
            endDate: moment(time_end * 1000),
            locale: {
                format: 'YYYY/MM/DD HH:mm'
            }
        });
        $('#iptTimeRange').on('apply.daterangepicker', function (ev, picker) {
            time_start = picker.startDate.unix();
            time_end = picker.endDate.unix();
        });


        function GotoPage(page) {
            if (page == 1) {
                $("#prePage").addClass('disabled');
            } else {
                $("#prePage").removeClass('disabled');
            }
            $("#spCurrentPage").text(page);

            var data = {
                is_pay: -1,
                order_code: order_code,
                user_id: user_id,
                time_start: time_start,
                time_end: time_end,
                page: page,
                page_size: pagesize,
            };

            window.history.pushState("searchResult", "搜索结果", "/kas/order_main?" + $.param(data));

            $.ajax({
                type: "GET",
                dataType: 'json',
                data: data,
                url: "/api/v1/auth/order/list",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + gokeep_token);
                }
            }).done(function (data) {
                Log(data);
                if (data.code == 0) {
                    var total = Math.ceil(data.total / pagesize);
                    if (total == 0) {
                        $("#noneResult").show();
                        return;
                    } else {
                        $("#noneResult").hide();
                    }
                    if ((data.result.length < pagesize) || (page == total)) {
                        $("#nextPage").addClass('disabled');
                    } else {
                        $("#nextPage").removeClass('disabled');
                    }

                    $("#spTotalPage").text(total);

                    var content = $("#tplOrderRow").render(data.result);
                    $("#frmResult").html(content);
                    $("#frmPagination").show();
                }
            }).fail(function (data) {
                Log("fail:", data);
                ShowMsg("获取列表失败");
            }); // end ajax
        }


        $("#btnSearch").click(function (event) {
            order_code = $("#iptOrderCode").val();
            user_id = $("#iptUserid").val();
            GotoPage(1);
        });

        GotoPage(1);

    </script>
</body>

</html>
{{ end }}