<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { BoxApi } from '@/utils/boxApi';
import { User, Lock } from '@element-plus/icons-vue';

const router = useRouter();
const route = useRoute();

// 获取主机地址（去掉端口）
const getHostAddress = () => window.location.hostname;
const getHostPort = () => '8000';


const loginForm = reactive({
  username: '',
  password: '',
  address: localStorage.getItem('rememberedAddress') || getHostAddress(),
  port: localStorage.getItem('rememberedPort') || getHostPort(),
  remember: false,
  serverSettings: false
});

const errorMessage = ref('');
const username = ref(localStorage.getItem('username') || '');
const alertToken = ref('');
const cookless = ref(false);

// 创建实例
let apiInstance: BoxApi | null = null;



// 加载页面时检查是否有记住的密码
onMounted(() => {
  const savedUsername = localStorage.getItem('username');
  const savedPassword = localStorage.getItem('rememberedPassword');
  // const savedAddress = localStorage.getItem('rememberedAddress');
  // const savedPort = localStorage.getItem('rememberedPort'); 
  if (savedUsername && savedPassword) {
    loginForm.username = savedUsername;
    loginForm.password = savedPassword;
    loginForm.remember = true; // 如果有记住的数据，将复选框设为选中状态
  }
});

const onSubmit = async () => {
  try {
    // if (!loginForm.address || !loginForm.port) {
    //   errorMessage.value = '请输入服务器地址和端口';
    //   return;
    // }
    const address = loginForm.serverSettings ? loginForm.address : getHostAddress();
    const port = loginForm.serverSettings ? loginForm.port : getHostPort();

    // 实例化 SuperboxApi
    apiInstance = new BoxApi(address, parseInt(port));

    // 调用 SuperboxApi 的 login 方法，传入 cookless 为 false
    const apiToken = await apiInstance.login(loginForm.username, loginForm.password, false);

    // 保存 token 到本地存储
    localStorage.setItem('alertToken', apiToken);
    localStorage.setItem('username', loginForm.username);
    localStorage.setItem('rememberedAddress', address);
    localStorage.setItem('rememberedPort', port);

    // 如果勾选了“记住密码”，将用户名、密码、地址和端口存入 localStorage
    if (loginForm.remember) {
      localStorage.setItem('rememberedPassword', loginForm.password);
    } else {
      // 如果未勾选“记住密码”，清除之前记住的数据
      localStorage.removeItem('rememberedPassword');
    }

    // 跳转到首页
    let redirect = route.query.redirect;
    if (Array.isArray(redirect)) {
      redirect = redirect[0]; // 如果 redirect 是数组，取第一个元素
    }
    router.push(redirect || '/'); // 确保 redirect 是字符串或使用默认的 '/'
  } catch (error) {
    // 捕获错误并显示错误信息
    errorMessage.value = '用户名或密码错误，或者连接服务器失败';
  }
};

const onReset = () => {
  loginForm.username = '';
  loginForm.password = '';
  // loginForm.address = '';
  // loginForm.port = '';
  loginForm.address = getHostAddress(); // 重置为当前主机地址
  loginForm.port = getHostPort(); // 重置为当前端口号
  loginForm.remember = false; // 重置记住密码复选框
  loginForm.serverSettings = false;
  errorMessage.value = '';
};
</script>


<template>
  <div class="main-layout">
    <div class="login-form">
      <div class="login-header">
        <el-row justify="center">
          <el-image src="/logo.png" fit="contain" />
        </el-row>
      </div>
      <div class="login-body">
        <el-form :model="loginForm" style="max-width: 600px;">
          <el-form-item v-show="loginForm.serverSettings">
            <el-input v-model="loginForm.address" placeholder="服务器地址" />
          </el-form-item>
          <el-form-item v-show="loginForm.serverSettings">
            <el-input v-model="loginForm.port" placeholder="端口" type="number" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="loginForm.username" placeholder="用户名">
              <template #prefix>
                <el-icon class="el-input__icon">
                  <User />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="loginForm.password" placeholder="密码" type="password">
              <template #prefix>
                <el-icon class="el-input__icon">
                  <Lock />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-row class="setting-row">
            <el-form-item>
              <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="loginForm.serverSettings">服务器设置</el-checkbox>
            </el-form-item>
          </el-row>
          <el-row justify="end">
            <el-form-item size="small" :gutter="30">
              <el-button type="primary" @click="onReset" plain>重置</el-button>
              <el-button type="primary" @click="onSubmit">登录</el-button>
            </el-form-item>
          </el-row>
          <el-row justify="center">
            <el-text class="error-message">{{ errorMessage }}</el-text>
          </el-row>
        </el-form>
      </div>
      <div class="login-footer">
        <el-row justify="end">
          <el-text class="plain-text">Powered by TuringAI</el-text>
        </el-row>
      </div>
    </div>
  </div>
</template>

<style scoped>
.main-layout {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('/login-bg.jpg');
  background-size: cover;
}

.login-form {
  min-width: 350px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 10px;
  background-color: #01111863;
}

.login-body {
  padding-top: 30px;
  padding-bottom: 5px;
  padding-left: 30px;
  padding-right: 30px;
}

.login-header {
  padding-top: 15px;
  padding-bottom: 15px;
  background-color: #01111863;
  border-radius: 10px 10px 0px 0px;
}

.login-footer {
  padding-top: 15px;
  padding-bottom: 20px;
  padding-right: 30px;
  padding-left: 30px;
  background-color: #01111863;
  border-radius: 0px 0px 10px 10px;
}

.plain-text {
  color: #9a9db3;
}

.error-message {
  color: red;
}

.setting-row {
  gap: 20px;
}
</style>
