<!DOCTYPE html>
<html lang="ko"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layouts/layout}"
>


<head></head>

<div layout:fragment="content">
    <!-- Page Heading -->
    <h1 class="h3 mb-4 text-gray-800">지난 주문</h1>

    <!-- Search Form -->
    <form id="search-form" class="mb-4">
        <div class="form-row align-items-center">
            <div class="col-auto my-1">
                <input type="date" class="form-control" id="start-date" name="startDate" />
            </div>
            <span> ~ </span>
            <div class="col-auto my-1">
                <input type="date" class="form-control" id="end-date" name="endDate" />
            </div>
            <div class="col-auto my-1">
                <button type="button" class="btn btn-outline-primary" id="confirm">조회</button>
            </div>
        </div>
        <input type="hidden" name="page" id="page" value="0" />
        <input type="hidden" id="select-start-date" />
        <input type="hidden" id="select-end-date" />
    </form>

    <h5 class="mb-4" id="header-date"></h5>

    <!-- Table -->
    <div class="table-responsive-xl">
        <table class="table">
            <thead>
            <tr>
                <th scope="col">주문번호</th>
                <th scope="col">주문상태</th>
                <th scope="col">주문시간</th>
                <th scope="col">주문상품</th>
                <th scope="col">결제금액</th>
                <th scope="col">닉네임</th>
            </tr>
            </thead>
            <tbody id="table-body">
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <nav aria-label="Page navigation example">
        <ul class="pagination justify-content-center" id="pagination">
        </ul>
    </nav>

    <script>
        const defaultOpts = {
            'visiblePages': 10,
            'initiateStartPageClick': false,
            'first': '<<',
            'prev': '<',
            'next': '>',
            'last': '>>',
            'inPageClick': function (event, page) {
                clickPage(page - 1);
            }
        };

        function init() {

        }

        function setEvent() {
            $("#confirm").click(() => {
                searchPrevOrder();
            });
        }

        function searchPrevOrder() {
            if (!dateValidation()) return null;
            $("#page").val(0);

            getPrevOrderData()
                .then((response) => response.json())
                .then((myJson) => {
                    if (myJson.code == "SUCCESS") {
                        drawHeader();
                        drawTable(myJson.data.orders, myJson.data.page.startPage + 1, myJson.data.page.totalPage);
                        drawPagination(myJson.data.orders, myJson.data.page.startPage + 1, myJson.data.page.totalPage);
                        return;
                    }

                    if (myJson.code == "ERROR") {
                        alert(myJson.message);
                        return;
                    }
                });
        }

        function clickPage(page) {
            if (!dateValidation()) return null;

            $("#page").val(page);
            getPrevOrderData()
                .then((response) => response.json())
                .then((myJson) => {
                    if (myJson.code == "SUCCESS") {
                        drawHeader();
                        drawTable(myJson.data.orders, myJson.data.page.startPage + 1, myJson.data.page.totalPage);
                        return;
                    }

                    if (myJson.code == "ERROR") {
                        alert(myJson.message());
                        return;
                    }
                });
        }

        function drawHeader() {
            let text = $("#start-date").val() + " ~ " + $("#end-date").val() + " 주문내역";
            $("#header-date").html(text);
        }

        function drawTable(data, startPage, totalPage) {
            $("#table-body").empty();

            if (data.length <= 0) {
                $("#table-body").html("<td>검색 결과가 없습니다.</td>");
                return;
            }

            const limit = 10;
            let html = "";
            let rownum = (startPage - 1) * limit
            for (let index = 0; index < data.length; index++) {
                let order = data[index];
                let tr = "<tr>";
                tr += "<th scope=\"row\">" + ++rownum + "</th>\n";
                tr += "<td>" + order.orderStatus + "</td>\n";
                tr += "<td>" + order.orderTime + "</td>\n";

                let orderItemNames = [];
                order.orderItems.forEach(orderItem => {
                    orderItemNames.push(orderItem.orderItemName);
                });

                tr += "<td><span class=\"d-inline-block text-truncate\" style=\"max-width: 80%\">"
                    + orderItemNames.join(", ")
                    + "</span></td>\n";
                tr += "<td>" + order.orderPrice + "</td>\n";
                tr += "<td>" + order.userName + "</td>\n";
                tr += "</tr>";
                html += tr;
            }
            $("#table-body").html(html);
        }

        function drawPagination(data, startPage, totalPages) {
            $("#pagination").twbsPagination('destroy');
            if (data.length <= 0) return;
            $("#pagination").twbsPagination($.extend({}, defaultOpts, {
                startPage: startPage,
                totalPages: totalPages,
            }));
        }

        function dateValidation() {
            const startDateTag = document.querySelector("#start-date");
            const endDateTag = document.querySelector("#end-date");

            if (!startDateTag.value) {
                alert("시작일을 선택해주세요.");
                startDateTag.focus();
                return false;
            }

            if (!endDateTag.value) {
                alert("종료일을 선택해주세요");
                endDateTag.focus();
                return false;
            }

            let startDate = startDateTag.valueAsDate;
            let endDate = endDateTag.valueAsDate;

            if (startDate.getTime() > endDate.getTime()) {
                alert("시작일은 종료일보다 클 수 없습니다.");
                startDateTag.focus();
                return false;
            }

            return true;
        }

        function getPrevOrderData() {
            let params = $("#search-form").serialize();
            return fetch(url.orderService + "/prevOrder?" + params);
        }
    </script>
</div>

</html>