<template>
  <div class="h-screen flex items-center justify-center flex-col">
    <div class="mb-8 text-3xl font-semibold">模板工具</div>
    <div class="w-1/5">
      <el-form :model="isRegister ? registerForm : form">
        <template v-if="!isRegister">
          <el-form-item label="账号" required>
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="密码" required>
            <el-input v-model="form.password" type="password" />
          </el-form-item>
          <el-form-item label="验证码" required v-if="false">
            <div class="flex items-center gap-2">
              <el-input v-model="form.captcha" />
              <img
                v-if="showCaptchaImage"
                :key="captchaUrl"
                :src="captchaUrl"
                alt="captcha"
                class="w-24 h-10 border rounded"
                @click="refreshCaptcha"
                @error="onCaptchaError"
              />
              <el-button
                v-if="showCaptchaImage"
                text
                type="primary"
                @click="refreshCaptcha"
                >刷新</el-button
              >
            </div>
          </el-form-item>
          <div class="flex justify-between">
            <el-button type="primary" @click="onSubmit">登录</el-button>
            <!-- <el-button link type="primary" @click="isRegister = true"
              >去注册</el-button
            > -->
          </div>
        </template>

        <template v-else>
          <el-form-item label="账号" required>
            <el-input v-model="registerForm.name" />
          </el-form-item>
          <el-form-item label="密码" required>
            <el-input v-model="registerForm.password" type="password" />
          </el-form-item>
          <el-form-item label="确认密码" required>
            <el-input v-model="registerForm.confirmPassword" type="password" />
          </el-form-item>
          <el-form-item label="验证码" required>
            <div class="flex items-center gap-2">
              <el-input v-model="registerForm.captcha" />
              <img
                v-if="showCaptchaImage"
                :key="captchaUrl"
                :src="captchaUrl"
                alt="captcha"
                class="w-24 h-10 border rounded"
                @click="refreshCaptcha"
                @error="onCaptchaError"
              />
              <el-button
                v-if="showCaptchaImage"
                text
                type="primary"
                @click="refreshCaptcha"
                >刷新</el-button
              >
            </div>
          </el-form-item>
          <div class="flex justify-between">
            <el-button type="primary" @click="onRegister">注册</el-button>
            <el-button link type="primary" @click="isRegister = false"
              >返回登录</el-button
            >
          </div>
        </template>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import useStore from "@/store";
import { storeToRefs } from "pinia";
import { getCaptchaNew, register } from "@/api/login";

const router = useRouter();
const { useUserStore } = useStore();
const { form } = storeToRefs(useUserStore);

let isRegister = ref(false);
let captchaUrl = ref("");

let registerForm = ref({
  name: "",
  password: "",
  confirmPassword: "",
  captcha: "",
});

// 控制是否显示图形验证码图片（默认隐藏）
const showCaptchaImage = ref(false);

async function loadCaptcha() {
  try {
    const res = await getCaptchaNew({ t: Date.now() });

    // 情况1：服务端直接返回图片（blob）
    if (res instanceof Blob) {
      // 若返回的是 JSON 文本（如 { code, data }），尝试解析
      if (res.type && !res.type.startsWith("image")) {
        const text = await res.text().catch(() => "");
        try {
          const json = JSON.parse(text || "{}");
          const base = json?.data || json?.image || "";
          if (typeof base === "string" && base.length) {
            captchaUrl.value = base.startsWith("data:")
              ? base
              : `data:image/png;base64,${base}`;
            return;
          }
        } catch (e) {
          // 非 JSON 文本，直接失败
        }
        throw new Error("验证码返回非图片且无法解析");
      }
      const url = URL.createObjectURL(res);
      captchaUrl.value = url;
      return;
    }

    // 情况2：返回的是 base64 字符串
    if (typeof res === "string") {
      captchaUrl.value = res.startsWith("data:")
        ? res
        : `data:image/png;base64,${res}`;
      return;
    }

    // 情况3：返回常规 JSON（通过业务码包装）
    if (res && res.code === 0) {
      const base = res?.data || res?.image;
      if (typeof base === "string") {
        captchaUrl.value = base.startsWith("data:")
          ? base
          : `data:image/png;base64,${base}`;
        return;
      }
    }

    throw new Error("无法识别的验证码响应格式");
  } catch (e) {
    ElMessage.error("验证码获取失败");
  }
}

function refreshCaptcha() {
  loadCaptcha();
}

function onCaptchaError() {
  // 兜底：直接使用代理路径，避免特殊响应类型导致渲染失败
  captchaUrl.value = `/api/captcha/new?t=${Date.now()}`;
}

onMounted(() => {
  // loadCaptcha();
});

async function onSubmit(params) {
  const res = await useUserStore.submit();
  if (res) {
    ElMessage.success("登录成功");
    router.push("/home");
  }
}

async function onRegister() {
  if (!registerForm.value.name || !registerForm.value.password) {
    ElMessage.error("账号或密码不能为空");
    return;
  }
  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    ElMessage.error("两次输入密码不一致");
    return;
  }
  if (!registerForm.value.captcha) {
    ElMessage.error("验证码不能为空");
    return;
  }
  try {
    const res = await register({
      name: registerForm.value.name,
      password: registerForm.value.password,
      captcha: registerForm.value.captcha,
    });
    if (res && res.code === 0) {
      ElMessage.success("注册成功，请登录");
      isRegister.value = false;
      // 可选：把注册账号填回登录表单
      useUserStore.$patch({
        form: {
          ...form.value,
          name: registerForm.value.name,
          password: registerForm.value.password,
          captcha: "",
        },
      });
      loadCaptcha();
    } else {
      ElMessage.error(res?.message || "注册失败");
    }
  } catch (e) {
    ElMessage.error("网络错误，注册失败");
  }
}
</script>

<style lang="scss" scoped></style>
