<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"
            mode="SECRET_COMBOBOX_MODE_DO_NOT_USE"
            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 { ref } from "vue";
import { store } from "@/store";
import { login } from "@/api/api";
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";
import { Store } from "@/types";
const router = useRouter();

store.pageInputs = {} as Store["pageInputs"];

let server = ref("");
// const servers = store.config.servers.map((v) => {
//   return { label: v.name, value: v.host };
// });
const servers = ref([
  { label: "线上环境", value: "https://www.markingcloud.com" },
]);

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";
// server.value = "https://www.markingcloud.com";
// loginName.value = "admin-wdsx";
// password.value = "wdsx!@#";
// server.value = "http://192.168.10.221:80";
// loginName.value = "admin-test";
// password.value = "123456";

const loginAction = () => {
  if (!server.value.startsWith("http")) {
    server.value = `http://${server.value}`;
  }
  let curServer = store.config.servers.find((v) => v.host === server.value) || {
    host: server.value,
    name: "自定义环境",
  };
  Object.assign(store.env, {
    server:
      store.config.servers.find((v) => v.host === server.value) || curServer,
    loginName: loginName.value,
    password: password.value,
  });
  if (!server.value) {
    message.info("请选择服务地址");
    return;
  }
  if (!loginName.value) {
    message.info("请输入账号");
    return;
  }
  if (!password.value) {
    message.info("请输入密码");
    return;
  }
  login()
    .then((res) => {
      Object.assign(store.env.user, res.data);
      router.push("/exam-list");
    })
    .catch((err) => {
      if (!err.toString().includes("404")) {
        message.error("登录失败，用户名或密码错误");
      }
    });
};
</script>
