<template>
    <el-form :inline="true" :model="config">
        <el-form-item label="邮箱">
            <el-input v-model="config.autoLoginEmail" placeholder="邮箱"/>
        </el-form-item>
        <el-form-item label="密码">
            <el-input v-model="config.autoLoginPwd" placeholder="密码" show-password type="password"/>
        </el-form-item>
    </el-form>
    <el-space direction="vertical" style="width: 100%">
        <el-text>请注意：密码为明文保存，注意保护个人信息安全</el-text>
        <el-text>当前会话状态：(不一定实时)
            <span v-if="isLoggedIn" style="color: #32CD32">已登陆</span>
            <span v-else style="color: red">已失效</span>
        </el-text>
        <el-text>确定此会话已失效时可
            <el-button :disabled="buttonDisabled" type="primary" @click="refreshLoggedIn">刷新登陆状态</el-button>
        </el-text>
    </el-space>
</template>

<script lang="ts">
export default {
    name: "AutoLoginForm"
}
</script>

<script lang="ts" setup>
import { computed, inject, ref } from "vue";
import { LoggerKey } from "../ts/class/Logger";
import { LocalConfigWrapperKey } from "../ts/class/LocalConfigWrapper";
import { ElMessage } from "element-plus";

const logger = inject(LoggerKey);
const localConfigWrapper = inject(LocalConfigWrapperKey);

const config = ref(localConfigWrapper.config);
const headerData = ref(sessionStorage.getItem('headerData'));
const isLoggedIn = computed(() => {
    return JSON.parse(headerData.value).user.state.isLoggedIn
});
const buttonDisabled = ref(false);
const refreshLoggedIn = async () => {
    if (config.value.autoLoginEmail && config.value.autoLoginPwd) {
        buttonDisabled.value = true;
        await fetch("https://www.torn.com/page.php?sid=Auth", {
            "headers": {
                "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
                "cache-control": "no-cache",
                "content-type": "application/x-www-form-urlencoded",
                "pragma": "no-cache",
                "sec-ch-ua-mobile": "?0",
                "sec-fetch-dest": "document",
                "sec-fetch-mode": "navigate",
                "sec-fetch-site": "same-origin",
                "sec-fetch-user": "?1",
                "upgrade-insecure-requests": "1"
            },
            "referrer": "https://www.torn.com/",
            "referrerPolicy": "strict-origin-when-cross-origin",
            "body": `email=${ config.value.autoLoginEmail }&password=${ config.value.autoLoginPwd }&redirectUrl=https%3A%2F%2Fwww.torn.com%2F&btnLogin=Login`,
            "method": "POST",
            "mode": "cors",
            "credentials": "include"
        });
        buttonDisabled.value = false;
        ElMessage("完成");
    } else {
        ElMessage("登陆信息不完整");
    }
};

</script>

<style scoped>

</style>