<?php
if ( !file_exists('./install/install.lock')) {
    header("Location: ./install/");
    exit;
}
require_once 'partials/head.php';
?>

<div id="pjax-container">
    <link rel="stylesheet" href="<?php echo __CSS__ ?>plugins/chat/chat.css">
    <link rel="stylesheet" href="<?php echo __CSS__ ?>plugins/hightlight/hightlight.css">
    <div class="content mb-3 animated fadeIn">
        <div class="block block-rounded h-100 mb-4 ">
            <?php if (__SYSTEM_MAINTENANCE__): ?>
                <div class="content content-full">
                    <div class="row justify-content-center">
                        <div class="col-md-8 col-lg-6 col-xl-4 py-6">
                            <div class="text-center">
                                <p><i class="fa fa-3x fa-cog fa-spin text-primary"></i></p>
                                <h1 class="h4 mb-1">系统正在维护中...</h1>
                                <h2 class="h6 fw-normal text-muted mb-3">请耐心等待</h2>
                            </div>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <div class="block-content block-content-full ">
                    <div class="chatBox-kuang" style="min-height: calc(100vh - 308px); display: block;">
                        <div class="chatBox-content" id="article-wrapper">
                            <div class="text-center" id="chatBoxMsg" style="display: block">
                                <h1 class="h3 font-semibold text-center mt-2 ml-auto mr-auto mb-4">ChatGPT</h1>
                                <div class="row">
                                    <div class="col-md-12 mb-5">
                                        <h2 class="fs-lg fw-normal"><svg stroke="currentColor" fill="none" stroke-width="1.5" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" class="h-6 w-6" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg> 示例</h2>
                                        <ul class="list-unstyled mt-3">
                                            <li><span class="opacity-50 btn btn-alt-secondary w-">"简单解释量子计算" →</span></li>
                                            <li><span class="opacity-50 btn btn-alt-secondary w- mt-3">"为一个10岁的孩子过生日有什么创意吗？" →</span></li>
                                            <li><span class="opacity-50 btn btn-alt-secondary w- mt-3">"如何用Javascript发出HTTP请求？" →</span></li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="input-group mt-4" id="fixed-block">
                        <button type="button" class="btn btn-alt-danger" id="clean">
                            <i class="far fa-trash-can"></i>
                        </button>
                        <label class="fs-sm text-muted" for="msg_context"></label>
                        <textarea class="form-control" style="resize: none;max-height: 60px;" rows="1" id="msg_context" name="msg_context" placeholder="请输入问题"></textarea>
                        <button id="send_message" onclick="send_message()" class="btn btn-alt-primary"><i class="fa fa-bolt-lightning opacity-50"></i> 发送 </button>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="block block-rounded block-content p-2" id="add_key" style="display: none;margin-bottom: 0!important;">
        <div class="text-center fw-semibold fs-sm">添加Key</div>
        <div class="mb-2">
            <label class="form-label fs-sm" for="key">API Key</label>
            <input type="password" class="form-control" id="key" name="key" placeholder="输入SK-开头的Key">
        </div>
        <button class="btn btn-sm btn-alt-primary me-1 m-1" id="addKey">
            <i class="fa fa-bolt opacity-50 me-1"></i> 保存到本地
        </button>
    </div>

    <div class="block block-rounded block-content p-2" id="preset" style="display: none;margin-bottom: 0!important;">
        <div class="text-center fw-semibold fs-sm">预设话术</div>
        <div class="form-group mb-2">
            <label class="form-label fs-sm" for="preset-text">预设话术</label>
            <select id="preset-text" class="form-select" onchange="insertPresetText()" size="10" multiple></select>
        </div>
    </div>

    <script>
        function openModalById (id)
        {
            layer.open({
                type   : 1,
                shade  : false, // 遮障可点击，透明度为0.5
                title  : false,
                content: $('#' + id),
            })
        }

        $('#addKey').click(() => {
            let key = app.getval('#key')
            if (!key.startsWith("sk-")) {
                app.btn('API Key不合法')
                return false;
            }
            localStorage.setItem('sk', key);
            if (localStorage.getItem('sk') === key) {
                app.btn('保存成功', null, '我知道了', () => {
                    layer.closeAll();
                })
            }
            else {
                app.btn('缓存失败')
            }
        })

        window.onload = () => {
            let key = localStorage.getItem('sk');
            if (key) {
                app.getval('#key', key)
            }
        }

        <?php if ( !__SYSTEM_MAINTENANCE__ && __NOTICE__): ?>
        app.btn('<?php echo __NOTICE_CONTENT ?>', '我知道了')
        <?php endif; ?>

        $(document).ready(function () {
            $.getJSON("<?php echo __JS__ ?>/config/chat.json", function (data) {
                var options = "";
                $.each(data, function (key, value) {
                    options += "<option value='" + value.content + "'>" + value.title + "</option>";
                });
                $("#preset-text").html(options);
            });
        });

        if (addCachedHtmlById('article-wrapper', 'user_' + getCookie('user'))) {
            console.log('历史对话信息加载成功')
        }
        else {
            console.log('未发现历史对话信息')
        }

        function send_message ()
        {
            if ($("#msg_context").is(':disabled')) {
                clearInterval(timer);
                $("#msg_context").val("");
                $("#msg_context").attr("disabled", false);
                autoresize();
                $("#send_message").html('<i class="fa fa-bolt-lightning opacity-50"></i> 发送 ');
                if (!isMobile()) $("#msg_context").focus();
            }
            else {
                send_post();
            }
            return false;
        }

        // 清空当前对话内容
        $("#clean").click(function () {
            app.btn('是否清空对话内容，本地缓存的数据也会一并清空', '确定', '取消', () => {
                localStorage.removeItem('user_' + getCookie('user'));
                $("#article-wrapper").children().not("#chatBoxMsg").remove();
                $("#chatBoxMsg").show()
                contextarray = [];
                layer.msg("清理完毕！");
                return false;
            })

        });
        const textarea = document.querySelector('#msg_context');
        textarea.addEventListener('keydown', function (event) {
            if (event.keyCode === 13 && !event.shiftKey) {
                event.preventDefault();
                send_message()
            }
            else if (event.keyCode === 13 && event.shiftKey) {
                const start = this.selectionStart;
                const end = this.selectionEnd;
                const value = textarea.value;
                textarea.value = value.substring(0, start) + '\n' + value.substring(end);
                textarea.selectionStart = textarea.selectionEnd = start + 1;
                event.preventDefault();
            }
        });
    </script>
</div>

<?php require_once 'partials/foot.php'; ?>
