<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8"/>
    <title>amis admin</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta
            name="viewport"
            content="width=device-width, initial-scale=1, maximum-scale=1"
    />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
    <link rel="stylesheet" title="default"
          href="/static/amis/sdk/sdk.css"/>
    <link rel="stylesheet" href="/static/amis/sdk/helper.css"/>
    <script src="/static/amis/sdk/sdk.js"></script>
    <script src="/static/amis/vue2.js"></script>
    <style>
        html,
        body,
        .app-wrapper {
            position: relative;
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }

        #login {
            position: absolute;
            top: 50%;
            left: 50%;
            margin: -150px 0 0 -150px;
            width: 300px;
            height: 300px;
        }

        #login h1 {
            color: #000000;
            text-align: center;
        }

        #loginh1 {
            font-size: 2em;
            margin: 0.67em 0;
        }

        .logininput {
            width: 278px;
            height: 18px;
            margin-bottom: 10px;
            outline: none;
            padding: 10px;
            font-size: 13px;
            color: #000000;
        }

        .but {
            width: 300px;
            min-height: 20px;
            display: block;
            background-color: #4a77d4;
            border: 1px solid #3762bc;
            color: #fff;
            padding: 9px 14px;
            font-size: 15px;
            line-height: normal;
            border-radius: 5px;
            margin: 0;
        }
    </style>
</head>
<body>
<div id="login">
    <h1 id="loginh1">登录</h1>
    <label for="username">账号</label><input class="logininput" type="text"
                                           required="required" placeholder="用户名"
                                           name="username"
                                           id="username"/>
    <label for="password">密码</label><input class="logininput" type="password"
                                           required="required"
                                           placeholder="密码" name="password"
                                           id="password"/>
    <button class="but" onclick="login()">登录</button>
</div>
<div id="root" class="app-wrapper" hidden></div>
<script>
    function login() {
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState === 4) {
                data = (new Function("return " + xmlhttp.responseText))()
                if (xmlhttp.status === 200) {
                    if (data.detail.code !== 0) {
                        window.alert(data.detail.msg)
                    } else {
                        document.getElementById('login').hidden = true;
                        document.getElementById("root").hidden = false;
                        main()
                    }
                } else {
                    window.alert(data.detail.msg)
                }
            }
        }
        xmlhttp.open(
            "post", "/admin/login", true,
        )
        xmlhttp.setRequestHeader('Content-Type', 'application/json')
        xmlhttp.send(
            JSON.stringify({
                "username": document.getElementById("username").value,
                "password":
                document.getElementById("password").value
            })
        )

    }

    function main() {
        let amis = amisRequire("amis/embed");

        const app = {
            type: "app",
            brandName: "Admin",
            logo: "/static/amis/logo.png",
            header: {
                type: "tpl",
                inline: false,
                className: "w-full",
                tpl:
                    '<div class="flex justify-between"><div>顶部区域左侧</div><div>顶部区域右侧</div></div>',
            },
            // footer: '<div class="p-2 text-center bg-light">底部区域</div>',
            // asideBefore: '<div class="p-2 text-center">菜单前面区域</div>',
            // asideAfter: '<div class="p-2 text-center">菜单后面区域</div>',
            api: "/admin/site",
        };

        function normalizeLink(to, location = window.location) {
            to = to || "";

            if (to && to[0] === "#") {
                to = location.pathname + location.search + to;
            } else if (to && to[0] === "?") {
                to = location.pathname + to;
            }

            const idx = to.indexOf("?");
            const idx2 = to.indexOf("#");
            let pathname = ~idx
                ? to.substring(0, idx)
                : ~idx2
                    ? to.substring(0, idx2)
                    : to;
            let search = ~idx ? to.substring(idx, ~idx2 ? idx2 : undefined) : "";
            let hash = ~idx2 ? to.substring(idx2) : location.hash;

            if (!pathname) {
                pathname = location.pathname;
            } else if (pathname[0] != "/" && !/^https?\:\/\//.test(pathname)) {
                let relativeBase = location.pathname;
                const paths = relativeBase.split("/");
                paths.pop();
                let m;
                while ((m = /^\.\.?\//.exec(pathname))) {
                    if (m[0] === "../") {
                        paths.pop();
                    }
                    pathname = pathname.substring(m[0].length);
                }
                pathname = paths.concat(pathname).join("/");
            }

            return pathname + search + hash;
        }

        const match = amisRequire("path-to-regexp").match;

        let amisScoped = amis.embed(
            "#root",
            app,
            {},
            {
                watchRouteChange: (fn) => {
                    window.addEventListener("hashchange", fn);
                    return () => {
                        window.removeEventListener("hashchange", fn);
                    };
                },
                jumpTo: (to) => {
                    location.hash = to;
                },
                responseAdpater(api, response, query, request) {//增加一个登陆弹框
                    if (response.detail.code === 401) {
                        document.getElementById("login").hidden = false
                        document.getElementById("root").hidden = true
                    }
                    return response;
                },
                isCurrentUrl: (to, ctx) => {
                    if (!to) {
                        return false;
                    }
                    const pathname = location.hash ? location.hash.substring(1) : "/";
                    const link = normalizeLink(to, {
                        ...location,
                        pathname,
                        hash: "",
                    });

                    if (!~link.indexOf("http") && ~link.indexOf(":")) {
                        return match(link, {
                            decode: decodeURIComponent,
                            strict: ctx?.strict ?? true,
                        })(pathname);
                    }

                    return pathname === link;
                },
            }
        );
    }

    const attachmentAdpator = (response) => {
        if (
            response &&
            response.headers &&
            response.headers['content-disposition']
        ) {
            const disposition = response.headers['content-disposition'];
            let filename = '';
            if (disposition && disposition.indexOf('attachment') !== -1) {
                let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/i;
                let matches = filenameRegex.exec(disposition);
                if (matches != null && matches[1]) {
                    filename = matches[1].replace(/['"]/g, '');
                }

                // 很可能是中文被 url-encode 了
                if (filename && filename.replace(/[^%]/g, '').length > 2) {
                    filename = decodeURIComponent(filename);
                }

                let type = response.headers['content-type'];
                let blob =
                    response.data.toString() === '[object Blob]'
                        ? response.data
                        : new Blob([response.data], {type: type});
                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                    window.navigator.msSaveBlob(blob, filename);
                } else {
                    let URL = window.URL || window.webkitURL;
                    let downloadUrl = URL.createObjectURL(blob);
                    if (filename) {
                        // use HTML5 a[download] attribute to specify filename
                        let a = document.createElement('a');
                        // safari doesn't support this yet
                        if (typeof a.download === 'undefined') {
                            window.location = downloadUrl;
                        } else {
                            a.href = downloadUrl;
                            a.download = filename;
                            document.body.appendChild(a);
                            a.click();
                        }
                    } else {
                        window.location = downloadUrl;
                    }
                    setTimeout(function () {
                        URL.revokeObjectURL(downloadUrl);
                    }, 100); // cleanup
                }

                return {
                    ...response,
                    data: {
                        status: 0,
                        msg: '文件即将开始下载。。'
                    }
                };
            }
        } else if (response.data.toString() === '[object Blob]') {
            return new Promise((resolve, reject) => {
                let reader = new FileReader();
                reader.addEventListener('loadend', e => {
                    const text = reader.result;

                    try {
                        resolve({
                            ...response,
                            data: {
                                ...JSON.parse(text)
                            }
                        });
                    } catch (e) {
                        reject(e);
                    }
                });

                reader.readAsText(response.data);
            });
        }

        return response;
    };

    const responseAdaptor = (api) => (value) => {
        let response = value.data;
        // 之前拼写错了，需要兼容

        if (env && env.responseAdaptor) {
            const url = api.url;
            const idx = api.url.indexOf('?');
            const query = ~idx ? qs.parse(api.url.substring(idx)) : {};
            const request = {
                ...api,
                query: query,
                body: api.data
            };
            response = env.responseAdaptor(api, response, query, request);
        } else {
            if (response.hasOwnProperty('errno')) {
                response.status = response.errno;
                response.msg = response.errmsg;
            } else if (response.hasOwnProperty('no')) {
                response.status = response.no;
                response.msg = response.error;
            }
        }

        const result = {
            ...value,
            data: response
        };
        return result;
    };

</script>

</body>
</html>
