<template>
  <div class="auth-wrapper">
    <!-- 左侧背景图区域 -->
    <div class="auth-left"></div>

    <!-- 右侧表单容器 -->
    <div class="auth-form-container">
      <!-- 登录表单 -->
      <el-form
        v-if="isLogin"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="116px"
        class="login-form"
      >
        <div class="form-header">
          <h2 class="form-title">{{ t("login.userTitle") }}</h2>
        </div>

        <div class="input-frame login-input-frame">
          <el-form-item label="账号：" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
        </div>

        <div class="input-frame login-input-frame">
          <el-form-item label="密码：" prop="password">
            <!-- 使用 Element Plus 的密码输入框 -->
            <el-input v-model="form.password" type="password" show-password />
          </el-form-item>
        </div>

        <!-- 错误提示区域 -->
        <div v-if="showError" class="error-message">
          {{ errorMessage }}
        </div>

        <div class="language-toggle-wrapper">
          <span class="text-toggle" @click="toggleLanguage">{{
            currentLanguageName
          }}</span>
        </div>

        <el-form-item>
          <div class="button-group">
            <el-button
              type="primary"
              @click="onSubmit"
              :loading="loading"
              class="login-button"
            >
              {{ t("login.loginButton") }}
            </el-button>
          </div>
          <div class="text-link-wrapper">
            <span class="text-toggle" @click="toggleForm">{{
              t("login.registerLink")
            }}</span>
          </div>
        </el-form-item>
      </el-form>

      <!-- 注册表单 -->
      <el-form
        v-else
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="login-form register-form" 
      >
        <div class="form-header">
          <h2 class="form-title">{{ t("register.title") }}</h2>
        </div>

        <!-- 调整后的注册账号输入框 -->
        <div class="input-frame register-input-frame register-account-frame">
          <el-form-item label="账号：" prop="name">
            <el-input v-model="registerForm.name" />
          </el-form-item>
        </div>

        <!-- 调整后的注册密码输入框 -->
        <div class="input-frame register-input-frame register-password-frame">
          <el-form-item label="密码：" prop="password">
            <!-- 使用 Element Plus 的密码输入框 -->
            <el-input
              v-model="registerForm.password"
              type="password"
              show-password
            />
          </el-form-item>
        </div>

        <div class="input-frame register-input-frame">
          <el-form-item 
            label="确认密码：" 
            prop="confirmPassword"
          >
            <!-- 使用 Element Plus 的密码输入框 -->
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              show-password
            />
          </el-form-item>
        </div>

        <!-- 成功/错误提示区域 -->
        <div v-if="showMessage" :class="messageType">
          {{ messageContent }}
        </div>

        <div class="language-toggle-wrapper">
          <span class="text-toggle" @click="toggleLanguage">{{
            currentLanguageName
          }}</span>
        </div>

        <el-form-item>
          <div class="button-group">
            <el-button
              type="primary"
              @click="onRegister"
              :loading="loading"
              class="login-button register-button-adjusted"
            >
              {{ t("register.registerButton") }}
            </el-button>
          </div>
          <div class="button-group register-link-container">
            <span @click="toggleForm" class="register-button">{{
              t("register.backToLoginButton")
            }}</span>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, watch, onMounted } from "vue";
import { ElForm, ElMessage } from "element-plus";
import type { FormRules } from "element-plus";
import { login, register } from "@/API/users";
import { changeLanguageAPI } from "@/API/admin";
import { useTokenStore } from "@/stores/mytoken";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";

// ============ 类型定义 ============
interface LoginForm {
  name: string;
  password: string;
}
interface RegisterForm {
  name: string;
  password: string;
  confirmPassword: string;
}

// ============ 核心实例 ============
const store = useTokenStore();
const { t, locale } = useI18n();
const router = useRouter();

// ============ 状态 ============
const isLogin = ref(true);
const loading = ref(false);
const showError = ref(false);
const errorMessage = ref("");

// 新增状态用于注册成功/失败提示
const showMessage = ref(false);
const messageContent = ref("");
const messageType = ref<"success-message" | "error-message">("error-message"); // 'success-message' 或 'error-message'

const form = reactive<LoginForm>({ name: "", password: "" });
const registerForm = reactive<RegisterForm>({
  name: "",
  password: "",
  confirmPassword: "",
});

const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const registerFormRef = ref<InstanceType<typeof ElForm> | null>(null);

// ============ 表单切换 ============
const toggleForm = () => {
  isLogin.value = !isLogin.value;
  showError.value = false; // 切换表单时隐藏错误提示
  showMessage.value = false; // 切换表单时也隐藏注册消息
};

/**
 * 切换语言并通知后端
 */
const toggleLanguage = async () => {
  // 计算新的语言
  const newLocale = locale.value === "zh" ? "en" : "zh";
  
  // 更新本地语言设置
  locale.value = newLocale;
  localStorage.setItem("lang", newLocale);

  try {
    // 发送语言切换信息到后端
    const response = await changeLanguageAPI({
      language: newLocale,
      userId: store.userInfo?.userId, // 修复：使用 userInfo?.userId
      timestamp: Date.now(), // 添加时间戳防止重复请求
    });

    if (!response.success) {
      console.warn('语言切换通知后端失败:', response.message);
      // 即使后端请求失败，前端语言切换仍然生效
    } else {
      console.log('语言切换已通知后端:', newLocale);
      // 可选：如果后端需要返回特定数据，可以处理响应
      if (response.message) {
        console.log('后端响应:', response.message);
      }
    }
  } catch (error) {
    console.error('发送语言切换请求到后端时出错:', error);
    // 错误处理，但不影响前端语言切换
  }
};

// ============ 计算属性 ============
const currentLanguageName = computed(() =>
  locale.value === "zh" ? "English" : "中文"
);

// ============ 显示错误消息 (保留原逻辑) ============
const showErrorMsg = (message: string) => {
  errorMessage.value = message;
  showError.value = true;

  // 3秒后自动隐藏消息
  setTimeout(() => {
    showError.value = false;
  }, 3000);
};

// ============ 显示通用消息 (新增) ============
const showMsg = (content: string, type: "success" | "error" = "success") => {
  messageContent.value = content;
  messageType.value = type === "success" ? "success-message" : "error-message";
  showMessage.value = true;

  // 3秒后自动隐藏消息
  setTimeout(() => {
    showMessage.value = false;
  }, 3000);
};

// ============ 登录逻辑 ============
const onSubmit = async () => {
  if (!formRef.value) return;

  try {
    // 验证表单
    await formRef.value.validate();
    loading.value = true;
    showError.value = false; // 开始验证时隐藏错误提示

    // 调用登录API
    const response = await login({
      name: form.name,
      password: form.password,
    });

    console.log("完整登录响应:", response);

    // 检查响应结构
    if (!response.data?.user) {
      throw new Error("后端返回的用户信息不完整");
    }

    // 提取用户信息
    const userData = response.data.user;

    if (!userData.id || !userData.name) {
      throw new Error("缺少必要的用户字段");
    }

    // --- 修改部分开始 (解决 TypeScript 错误) ---
    // 确定 loginType 的值
    // 假设后端返回的字段是 userType
    let loginTypeFromResponse = userData.userType;

    // 如果后端没有返回 userType，使用默认值 'user' 以避免程序崩溃
    // 你可以根据实际业务需求调整默认值或处理逻辑
    if (!loginTypeFromResponse) {
       console.warn("后端未返回 userType，使用默认值 'user'");
       loginTypeFromResponse = 'user';
    }

    // 保存用户信息到store (包含必需的 loginType)
    store.saveToken({
      userId: Number(userData.id),
      name: userData.name,
      loginType: loginTypeFromResponse, // 确保提供 loginType
      // 如果 UserInfo 还有其他必需字段，也需要在这里提供
    });
    // --- 修改部分结束 ---

    // 使用 Element Plus 的成功提示
    ElMessage.success(t("login.loginSuccess"));

    // 跳转到目标页面
    await router.push({ name: "samplingMethodDevice1" });
  } catch (error: any) {
    console.error("登录失败:", {
      error: error.message,
      stack: error.stack,
      response: error.response?.data,
    });

    // 显示错误消息
    const errorMsg =
      error.response?.data?.message ||
      error.message ||
      t("login.loginFailed"); // 使用翻译键
    showErrorMsg(errorMsg);
    // 使用 Element Plus 的错误提示
    ElMessage.error(errorMsg);
  } finally {
    loading.value = false;
  }
};

// ============ 注册逻辑 ============
const onRegister = async () => {
  if (!registerFormRef.value) return;
  try {
    await registerFormRef.value.validate();
    loading.value = true;
    showError.value = false; // 开始验证时隐藏错误提示
    showMessage.value = false; // 开始验证时隐藏消息

    // 调用注册API
    const res = await register({
      name: registerForm.name,
      password: registerForm.password,
    });

    // 注册成功
    if (res.data?.message) {
      // 显示注册成功消息
      showMsg(t("register.registerSuccess"), "success");
      ElMessage.success(t("register.registerSuccess"));

      // 延迟一段时间后自动跳转到登录页并填充信息
      setTimeout(() => {
        // 切换到登录表单
        isLogin.value = true;

        // 将注册的用户名和密码填入登录表单
        form.name = registerForm.name;
        form.password = registerForm.password; // 填充密码

        // 清空注册表单
        registerForm.name = "";
        registerForm.password = "";
        registerForm.confirmPassword = "";

        // 可选：给用户一个提示
        ElMessage.info(t("register.autoLoginPrompt"));
      }, 1500); // 1.5秒后执行
    } else {
      const errorMsg = res.data?.message || t("register.registerFailed");
      showMsg(errorMsg, "error");
      ElMessage.error(errorMsg);
    }
  } catch (error: any) {
    console.error("注册异常:", error);
    const errorMsg =
      error?.response?.data?.message || t("register.registerFailed");
    showMsg(errorMsg, "error");
    ElMessage.error(errorMsg);
  } finally {
    loading.value = false;
  }
};

// ============ 校验规则 ============
const createRules = (): { rules: FormRules; registerRules: FormRules } => {
  const rules: FormRules = {
    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: FormRules = {
    name: rules.name,
    password: rules.password,
    confirmPassword: [
      {
        required: true,
        message: t("validation.confirmPasswordRequired"),
        trigger: "blur",
      },
      {
        validator: (_rule, value: string, callback) => {
          if (value !== registerForm.password)
            callback(new Error(t("validation.passwordMismatch")));
          else callback();
        },
        trigger: "blur",
      },
    ],
  };
  return { rules, registerRules };
};

let { rules, registerRules } = createRules();

watch(locale, () => {
  const newRules = createRules();
  rules = newRules.rules;
  registerRules = newRules.registerRules;
});

watch(
  () => registerForm.password,
  () => {
    registerFormRef.value?.validateField("confirmPassword");
  }
);

onMounted(() => {
  console.log("登录/注册页初始化", {
    form,
    registerForm,
    locale: locale.value,
  });
});
</script>

<style scoped>
.auth-wrapper {
  display: flex;
  height: 100vh;
  background-color: #f6f6f6;
  position: relative;
}
.auth-left {
  width: 35%;
  background: url("@/assets/login-bg.png") no-repeat center/cover;
}
.auth-form-container {
  width: 55%;
  padding: 0 40px 0 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.login-form {
  width: 100%;
  max-width: 700px;
  padding: 40px 30px;
  margin-top: 50px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 15px;
}
.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
  margin-top: 20px;
}
.form-title {
  font-size: 32px;
  font-weight: 600;
  color: #333;
}
.language-toggle-wrapper {
  text-align: right;
  margin: 15px 0 20px;
}
:deep(.el-form-item__label) {
  float: none;
  display: block;
  text-align: left;
  font-size: 24px;
  padding-bottom: 8px;
  color: #7e7878;
  white-space: nowrap; /* 防止标签内文字换行 */
  overflow: hidden;
  text-overflow: ellipsis;
}
/* 更新输入框样式以适应 Element Plus 的结构 */
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset; /* 模拟之前的边框 */
  border-radius: 0;
}
:deep(.el-input__inner) {
  height: 50px;
  font-size: 20px;
  background-color: #fff;
  padding: 0 15px;
}
/* 更新密码图标按钮样式 */
:deep(.el-input__suffix) {
  cursor: pointer;
  font-size: 20px;
  color: #aaa;
  margin-right: 10px;
}

.login-button {
  background: linear-gradient(to right, #8df9f0, #26b046);
  width: 100%;
  max-width: 300px; /* 缩小按钮宽度 */
  height: 56px;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 24px;
  cursor: pointer;
  margin-top: 10px;
  margin: 10px auto; /* 居中显示 */
  display: block; /* 使 margin: auto 生效 */
}
.login-button:hover {
  opacity: 0.9;
}
.register-button {
  display: block;
  text-align: center;
  color: #478bf0;
  font-size: 18px;
  cursor: pointer;
  padding: 10px 0;
  width: 100%;
}
.register-button:hover {
  color: #357ae8;
  text-decoration: underline;
}
.button-group {
  display: flex;
  justify-content: center;
  width: 100%;
}
.text-toggle {
  color: #478bf0;
  font-size: 16px;
  cursor: pointer;
}
.text-toggle:hover {
  color: #357ae8;
  text-decoration: underline;
}
.text-link-wrapper {
  text-align: center;
  margin-top: 20px;
}

/* 错误提示样式 */
.error-message,
.success-message {
  font-size: 16px;
  text-align: center;
  margin: 15px 0;
  animation: fadeIn 0.3s ease-out forwards;
  padding: 10px;
  border-radius: 4px;
}
.error-message {
  color: #f56c6c;
  background-color: #fef0f0;
  border: 1px solid #fde2e2;
}
.success-message {
  color: #67c23a;
  background-color: #f0f9ec;
  border: 1px solid #e1f3d8;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 针对登录和注册表单中的标签 */
.login-form :deep(.el-form-item__label),
.register-form :deep(.el-form-item__label) {
    /* 为登录和注册表单中的标签设置一个稍大的最大宽度，以适应"确认密码"等较长标签 */
    max-width: 200px; /* 根据实际需要调整 */
    width: auto;
    text-align: right; /* 标签靠右对齐 */
    flex-shrink: 0; /* 防止标签被压缩 */
    margin-right: 15px; /* 标签和输入框之间的间距 */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 针对登录和注册表单中的内容区域 */
.login-form :deep(.el-form-item__content),
.register-form :deep(.el-form-item__content) {
    display: flex;
    justify-content: flex-end; /* 内容整体靠右 */
    width: 100%;
}

/* 针对登录和注册表单中的输入框包装器 */
.login-form :deep(.el-input__wrapper),
.register-form :deep(.el-input__wrapper) {
    max-width: 350px; /* 设置你想要的统一缩短后的宽度 */
    width: 100%; 
    margin-left: 0; 
}

/* 特别为登录和注册表单的输入框框架增加类名并设置间距 */
.login-input-frame,
.register-input-frame {
  margin-left: 48px;
}

/* --- 修改部分：为注册表单的账号和密码输入框容器添加特定类名并设置新的左边距 --- */
.register-form .register-account-frame,
.register-form .register-password-frame {
  margin-left: 96px; /* 原来的 48px + 新增的 20px */
}
/* --------------------------------------------------------------------------------- */

/* 确认密码输入框间距保持不变 */
.register-form .input-frame:last-of-type {
  margin-bottom: 20px; /* 或者你希望的其他值 */
}

/* 注册按钮特殊调整 */
.register-button-adjusted {
  max-width: 250px; 
}
</style>



