<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>QUERY TOOL</title>
    <script type="text/javascript" src="/ex_dev_tool/static/lib/jquery/jquery.js"></script>
    <script type="text/javascript" src="/ex_dev_tool/static/lib/bootstrap/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="/ex_dev_tool/static/lib/bootstrap/css/bootstrap.min.css"/>
    <script type="text/javascript" src="/ex_dev_tool/static/src/jsontotable.js"></script>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
            text-align: left; /* 默认左对齐 */
        }
        td {
            width: 33.3%;
        }
        td.center {
            text-align: center; /* 按钮居中 */
        }
    </style>
</head>
<body>
<div class="container center-block">
    <p class="bg-success" align="center">QUERY TOOLS FOR DEVELOPER</p>
    <textarea id="query_input" class="form-control" rows="3">select id from res_partner limit 10</textarea>

    <table>
        <tr>
            <td>开始执行时间：<span id="start_time"></span></td>
            <td class="center"><button id="query_btn" onclick="fillTable()" class="btn btn-primary">查询</button></td>
            <td>执行结束时间：<span id="end_time"></span></td>
        </tr>
    </table>
</div>
<br/>

<div id="container" class="container center-block"></div>
<script>
    function fillTable() {
        // 检查是否有开始时间但没有结束时间
        if ($("#start_time").text() && !$("#end_time").text()) {
            alert("查询正在进行中，请等待当前查询完成后再尝试。");
            return;
        }

        $("#container").empty();

        let query_str = $("#query_input").val();

        // 将SQL中的+号转为base64，避免被转成空格
        query_str = query_str.replace(/\+/g, '%2B')
        console.log(query_str);

        $("#start_time").text(new Date().toLocaleString());
        $("#end_time").text("");

        $.ajax({
            url: "/ex/tool/sql/query?q=" + encodeURI(query_str),
            success: function (data) {
                const jsonHtmlTable = ConvertJsonToTable(JSON.parse(data), 'jsonTable', "table table-bordered table-hover", 'Download');
                const container = $("#container");
                container.empty();
                container.append(jsonHtmlTable);
                $("#end_time").text(new Date().toLocaleString());
            }
        });
    }
</script>
</body>
</html>
