<template>
  <div class="login-flex">
    <div class="login">
      <div class="logo"><img src="img/logo_blue.png" /></div>
      <a-form @submit="loginAction">
        <div>
          <a-select
            style="width: 100%; text-align: left"
            v-model:value="server"
            :options="servers"
            placeholder="请选择服务地址"
          >
          </a-select>
        </div>
        <div>
          <a-input
            v-model:value="loginName"
            id="loginName-input"
            type="text"
            placeholder="请输入账号"
          />
        </div>
        <div>
          <a-input
            v-model:value="password"
            id="password-input"
            type="password"
            placeholder="请输入密码"
            @press-enter="loginAction"
          />
        </div>
        <div><a href="##" id="login-button" @click="loginAction">登录</a></div>
      </a-form>
    </div>
    <div class="ft">
      Copyright © 2011-2021 www.qmth.com.cn, All Rights Reserved
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { store } from "@/store";
import { login } from "@/api/api";
import { useRouter } from "vue-router";
const router = useRouter();

let server = ref(null);
const servers = store.config.servers.map((v) => {
  return { label: v.name, value: v.host };
});

let loginName = ref("");
let password = ref("");

// FIXME: restore original state
// onMounted(() => {
//   window.localStorage.clear();
// });
// server.value = "http://192.168.10.224:80";
// loginName.value = "admin-test";
// password.value = "123456";

const loginAction = () => {
  Object.assign(store.env, {
    server: store.config.servers.find((v) => v.host === server.value),
    loginName: loginName.value,
    password: password.value,
  });
  if (!server.value) {
    alert("请选择服务地址");
    return;
  }
  if (!loginName.value) {
    alert("请输入账号");
    return;
  }
  if (!password.value) {
    alert("请输入密码");
    return;
  }
  login()
    .then((res) => {
      Object.assign(store.env.user, res.data);
      router.push("/exam-list");
    })
    .catch((err) => {
      console.log(err);
      alert("登陆失败，用户名或密码错误");
    });
};
</script>
