<script setup>
import { ref } from 'vue';
import { ElInput, ElButton, ElCheckbox, ElForm, ElFormItem, ElMessage } from 'element-plus';
import 'element-plus/dist/index.css';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';

const store = useStore();
const router = useRouter();

const username = ref('');
const password = ref('');
const rememberMe = ref(false);

const handleLogin = async () => {
  console.log('Logging in with', { username: username.value, password: password.value, rememberMe: rememberMe.value });

  try {
    const response = await store.dispatch('authentication/login', {
      username: username.value,
      password: password.value,
    });

    if (response.status === 200) {
      ElMessage.success('登录成功');
      router.push('/profile');
    } else {
      ElMessage.error('登录失败，请稍后再试');
    }
  } catch (error) {
    if (error.response && error.response.status === 401) {
      ElMessage.error('用户名或密码错误');
    } else {
      ElMessage.error('登录失败，请稍后再试');
    }
  }
};
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <h2>测盟汇管理系统</h2>
      <ElForm @submit.prevent="handleLogin">
        <ElFormItem>
          <label for="username">
            <i class="fas fa-user"></i> 账号
          </label>
          <ElInput v-model="username" type="text" id="username" placeholder="请输入您的账号" required />
        </ElFormItem>
        <ElFormItem>
          <label for="password">
            <i class="fas fa-lock"></i> 密码
          </label>
          <ElInput v-model="password" type="password" id="password" placeholder="请输入您的密码" required />
        </ElFormItem>
        <ElFormItem>
          <ElCheckbox v-model="rememberMe" id="rememberMe">记住密码</ElCheckbox>
        </ElFormItem>
        <ElFormItem>
          <ElButton type="primary" native-type="submit" class="login-button">登录</ElButton>
        </ElFormItem>
        <ElFormItem>
          <ElButton type="text" @click="() => $router.push('/register')">注册</ElButton>
        </ElFormItem>
      </ElForm>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: url('background.jpg') no-repeat center center;
  background-size: cover;
}

.login-box {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
  width: 20%;
}

h2 {
  margin-bottom: 1rem;
}

.el-form-item {
  margin-bottom: 1rem;
  text-align: left;
}

.el-form-item label {
  display: block;
  margin-bottom: 0.5rem;
}

.el-input {
  width: 100%;
}

.el-button {
  width: 100%;
  padding: 0.75rem;
}

.el-button--primary {
  background-color: #007bff;
  color: white;
}

.el-button--primary:hover {
  background-color: #0056b3;
}
</style>
