<template>
  <div class="auth">
    <!-- 语言切换按钮 -->
    <div class="language-toggle">
      <el-button @click="switchLanguage('en')">English</el-button>
      <el-button @click="switchLanguage('zh')">中文</el-button>
    </div>

  <!-- 登录表单 -->
    <el-form
      v-if="isLogin"
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <h2>{{ $t('login.title') }}</h2>
      <el-form-item prop="name" :label="$t('login.username')">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item prop="password" :label="$t('login.password')">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="loading">
          {{ $t('login.loginButton') }}
        </el-button>
        <el-button @click="toggleForm">{{ $t('login.registerButton') }}</el-button>
        <el-button @click="mockUserLogin">{{ $t('login.mockLoginButton') }}</el-button>
      </el-form-item>
    </el-form>

    <!-- 注册表单 -->
    <el-form
      v-else
      ref="registerFormRef"
      :model="registerForm"
      :rules="registerRules"
      label-width="100px"
    >
      <h2>{{ $t('login.registerButton') }}</h2>
      <el-form-item prop="name" :label="$t('login.username')">
        <el-input v-model="registerForm.name"></el-input>
      </el-form-item>
      <el-form-item prop="password" :label="$t('login.password')">
        <el-input type="password" v-model="registerForm.password"></el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword" label="确认密码">
        <el-input
          type="password"
          v-model="registerForm.confirmPassword"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onRegister" :loading="loading">
          {{ $t('login.registerButton') }}
        </el-button>
        <el-button @click="toggleForm">{{ $t('login.loginButton') }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>


<script lang="ts" setup>
import { useI18n } from 'vue-i18n';
import { reactive, ref, computed } from "vue";
import { ElMessage, ElForm } from "element-plus";
import axios from "axios";
import { login, register } from "@/API/users"; // 假设已封装好的接口
import { useRouter, useRoute } from "vue-router";
import { useTokenStore } from "@/stores/mytoken";

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

const isLogin = ref(true); // 控制显示登录或注册表单
const { t, locale } = useI18n();

const form = reactive({
  name: "",
  password: "",
});

const switchLanguage = (lang: string) => {
  locale.value = lang;
};

const registerForm = reactive({
  name: "",
  password: "",
  confirmPassword: "",
});
const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const registerFormRef = ref<InstanceType<typeof ElForm> | null>(null);
const loading = ref(false);

// 切换登录/注册表单
const toggleForm = () => {
  isLogin.value = !isLogin.value;
};

// 密码登录提交
const onSubmit = async () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;
    loading.value = true;
    try {
      const res = await login({ name: form.name, password: form.password });
      if (res.data.success) {
        console.log(t("login.successMessage"), res.data);
        const userInfo = {
          userId: parseInt(res.data.userId),
          name: res.data.name,
          loginType: "password",
        };
        store.saveToken(userInfo);
        console.log(t("login.tokenSaved"), store.token);
        ElMessage.success(t("login.successMessage"));
        const redirectPath =
          typeof route.query.redirect === "string" ? route.query.redirect : "/";
        router.push(redirectPath);
      } else {
        ElMessage.error(res.data.message || t("login.errorMessage"));
      }
    } catch (error) {
      if (axios.isAxiosError(error)) {
        console.error(
          `HTTP Error: ${error.message}, status code: ${error.response?.status}`
        );
        ElMessage.error(
          `${t("login.httpError")}: ${error.response?.statusText}`
        );
      } else {
        console.error(error);
        ElMessage.error(t("login.errorMessage"));
      }
    } finally {
      loading.value = false;
    }
  });
};

// 模拟普通用户登录
const mockUserLogin = () => {
  const mockUserInfo = { userId: 1, name: t("login.mockUser"), loginType: "mock" }; // 添加loginType字段以示区别
  store.saveToken(mockUserInfo);
  ElMessage.success(t("login.mockLoginSuccess"));
  const redirectPath =
    typeof route.query.redirect === "string" ? route.query.redirect : "/";
  router.push(redirectPath);
};

// 注册提交
const onRegister = async () => {
  if (!registerFormRef.value) return;
  registerFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return;

    if (registerForm.password !== registerForm.confirmPassword) {
      ElMessage.error(t("register.passwordMismatch"));
      return;
    }

    try {
      const res = await register({
        name: registerForm.name,
        password: registerForm.password,
      });
      if (res.data.success) {
        ElMessage.success(t("register.successMessage"));
        toggleForm(); // 切换回登录表单
      } else {
        ElMessage.error(res.data.message || t("register.errorMessage"));
      }
    } catch (error) {
      if (axios.isAxiosError(error)) {
        console.error(
          `HTTP Error: ${error.message}, status code: ${error.response?.status}`
        );
        ElMessage.error(
          `${t("register.httpError")}: ${error.response?.statusText}`
        );
      } else {
        console.error(error);
        ElMessage.error(t("register.errorMessage"));
      }
    } finally {
      loading.value = false;
    }
  });
};

// 验证规则
const rules = reactive({
  name: [{ required: true, message: t("validation.usernameRequired"), trigger: "blur" }],
  password: [
    { required: true, message: t("validation.passwordRequired"), trigger: "blur" },
    {
      min: 3,
      max: 16,
      message: t("validation.passwordLength"),
      trigger: "blur",
    },
  ],
});

const registerRules = reactive({
  name: [{ required: true, message: t("validation.usernameRequired"), trigger: "blur" }],
  password: [
    { required: true, message: t("validation.passwordRequired"), trigger: "blur" },
    {
      min: 3,
      max: 16,
      message: t("validation.passwordLength"),
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: t("validation.confirmPasswordRequired"), trigger: "blur" },
    {
      validator: (
        rule: any,
        value: string,
        callback: (error?: Error) => void
      ) => {
        if (value !== registerForm.password) {
          callback(new Error(t("validation.passwordMismatch")));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});
</script>


<style scoped>
.auth {
  background-color: #f5f7fa; /* 更浅的颜色背景 */
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-form {
  width: 350px; /* 稍微宽一点 */
  padding: 40px;
  background-color: #ffffff;
  border-radius: 15px; /* 圆角更大 */
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  position: relative;
}

.form-header {
  display: flex;
  justify-content: flex-end; /* 将内容推到右侧 */
  margin-bottom: 25px; /* 加大间距 */
}

.language-toggle {
  position: absolute;
  top: 10px;
  right: 10px; /* 右上角位置 */
  padding: 8px 15px; /* 更大的内边距 */
  font-size: 14px; /* 更大的字体 */
  color: #409eff; /* 蓝色文字 */
  border: none; /* 去掉边框 */
  background: transparent; /* 透明背景 */
  cursor: pointer;
  transition: all 0.3s ease; /* 平滑过渡 */
}

.language-toggle:hover {
  color: #66b1ff; /* 悬停时颜色加深 */
}

.form-title {
  text-align: center; /* 标题居中 */
  margin-bottom: 20px; /* 下方间距 */
}

.el-form-item__label {
  font-weight: bold; /* 标签加粗 */
  color: #333; /* 字体颜色更深 */
}

.el-input__inner {
  border: 1px solid #dcdcdc; /* 边框颜色 */
  border-radius: 5px; /* 圆角 */
  padding: 10px; /* 内边距 */
  transition: border-color 0.3s ease; /* 平滑过渡 */
}

.el-input__inner:focus {
  border-color: #409eff; /* 聚焦时边框颜色 */
}

.el-button {
  width: 50%; /* 宽度占满 */
  margin-top: 20px; /* 上下间距 */
  transition: background-color 0.3s ease; /* 平滑过渡 */
}

.el-button--primary {
  background-color: #409eff; /* 主要按钮颜色 */
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff; /* 悬停时颜色加深 */
  border-color: #66b1ff;
}

.el-button:not(.el-button--primary):hover {
  background-color: #f5f7fa; /* 其他按钮悬停背景色 */
  color: #409eff; /* 文字颜色 */
}
</style>



