<script lang="ts" setup>
import { computed, ref, reactive, nextTick } from 'vue';
import { $t } from '@vben/locales';
import { useAuthStore } from '#/store';
import { Button, Input, Space, message, Card, Form, FormItem, Spin } from 'ant-design-vue';
// 这里假设你的api定义文件路径正确，且导出正确
import { setup2faApi, verify2faApi } from '#/api';
// 需要安装 qrcode: pnpm add qrcode && pnpm add -D @types/qrcode
import QRCode from 'qrcode';
import Title from './auth-title.vue';

defineOptions({ name: 'Login' });

const authStore = useAuthStore();
const loading = ref(false);

// 状态控制：1 为输入账号阶段，2 为输入密码和验证码阶段
const step = ref(1);

// 二维码图片的 Base64 数据
const qrCodeUrl = ref('');

// 显示模式：'qrcode' 显示二维码，'secret' 显示密钥
const displayMode = ref('qrcode');

// 计算属性：判断是否需要显示2FA信息区域
const show2faInfo = computed(() => {
  return formState.secretKey && formState.qrCodeUrl;
});

// 表单数据
const formState = reactive({
  username: '',
  password: '',
  code: '',   // 验证码
  secretKey: '', // 从后端获取的秘钥
  qrCodeUrl: ''  // 从后端获取的用于生成二维码的地址
});

/**
 * 第一步：验证账号并获取 2FA 设置信息
 */
const handleVerifyusername = async () => {
  if (!formState.username) {
    message.warning('请输入账号');
    return;
  }

  try {
    loading.value = true;
    // 调用 setup 接口
    const res = await setup2faApi({ username: formState.username });
    formState.secretKey = res.data?.secretKey;
    formState.qrCodeUrl = res.data?.qrCodeUrl

    // 生成二维码
    if (formState.qrCodeUrl) {
      qrCodeUrl.value = await QRCode.toDataURL(formState.qrCodeUrl);
          displayMode.value = 'qrcode'; // 默认显示二维码
    }

    // 切换到第二步
    step.value = 2;
  } catch (error) {
    console.error(error);
    // message.error('验证失败或账号不存在'); 
  } finally {
    loading.value = false;
  }
};

/**
 * 第二步：提交登录
 */
const handleLogin = async () => {
  if (!formState.password || !formState.code) {
    message.warning('请输入密码和验证码');
    return;
  }
  
  try {
    loading.value = true;
    // 传入 4 个值：账号、密码、验证码、秘钥
    const params = {
      username: formState.username,
      password: formState.password,
      code: parseInt(formState.code),
      secretKey: formState.secretKey
    };
    await authStore.authLoginCode(params);
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};

/**
 * 重置流程（可选：方便用户切回修改账号）
 */
const handleReset = () => {
  step.value = 1;
  formState.password = '';
  formState.code = '';
  formState.secretKey = '';
  qrCodeUrl.value = '';
  displayMode.value = 'qrcode';
};

/**
 * 切换显示模式
 */
const toggleDisplayMode = () => {
  displayMode.value = displayMode.value === 'qrcode' ? 'secret' : 'qrcode';
};

/**
 * 复制文本到剪贴板
 */
const copyToClipboard = (text: string) => {
  // 创建临时textarea元素
  const textArea = document.createElement('textarea');
  textArea.value = text;
  textArea.style.position = 'fixed';
  textArea.style.left = '-999999px';
  textArea.style.top = '-999999px';
  document.body.appendChild(textArea);
  
  // 选中并复制文本
  textArea.focus();
  textArea.select();
  
  try {
    const successful = document.execCommand('copy');
    if (successful) {
      message.success('密钥已复制到剪贴板');
    } else {
      message.error('复制失败，请手动复制密钥');
    }
  } catch (err) {
    message.error('复制失败，请手动复制密钥');
  }
  
  // 清理临时元素
  document.body.removeChild(textArea);
};

</script>

<template>
  <div class="login-wrapper flex items-center justify-center">
    <div class="login-card w-full max-w-md">
      <div class="">
        <Title>
          <slot name="title">
            {{ `${$t('authentication.welcomeBack')} 👋🏻` }}
          </slot>
          <template #desc>
            <span class="text-muted-foreground">
              <slot name="subTitle">
                {{ $t('authentication.loginSubtitle') }}
              </slot>
            </span>
          </template>
        </Title>

        <Form layout="vertical" :model="formState" class="space-y-6">

          <!-- 始终显示：账号输入 -->
          <FormItem label="账号" class="mb-0">
            <Input v-model:value="formState.username" placeholder="请输入账号" :disabled="step === 2" allow-clear
              size="large" class="w-full" @pressEnter="step === 1 ? handleVerifyusername() : null" />
          </FormItem>

          <!-- 步骤 2 显示的内容 -->
          <div v-if="step === 2" class="step-content space-y-6">

            <!-- 2FA 信息展示区域 -->
            <div v-if="show2faInfo" class="auth-info-container">
              <!-- 切换按钮 -->
              <div class="flex justify-center mb-4 qiehuan11">
                <div class="inline-flex rounded-md shadow-sm" role="group">
                  <button
                    type="button"
                    class=" text-sm font-medium ddd ddd1  border"
                    :class="displayMode === 'qrcode' 
                      ? 'bg-blue-600 text-white border-blue-600' 
                      : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50'"
                    @click="displayMode = 'qrcode'"
                  >
                    二维码
                  </button>
                  <button
                    type="button"
                    class=" text-sm font-medium ddd border"
                    :class="displayMode === 'secret' 
                      ? 'bg-blue-600 text-white border-blue-600' 
                      : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50'"
                    @click="displayMode = 'secret'"
                  >
                    密钥
                  </button>
                </div>
              </div>

              <!-- 二维码展示 -->
              <div v-if="displayMode === 'qrcode'" class="qr-container bg-gray-50 border border-dashed border-gray-300 rounded-lg p-4 text-center">
                <p class="qr-tip text-sm text-gray-500 mb-3">请使用 Authenticator 扫描下方二维码</p>
                <img v-if="qrCodeUrl" :src="qrCodeUrl" alt="2FA QR Code" class="qr-img w-32 h-32 mx-auto" />
                <div v-else class="qr-placeholder w-32 h-32 mx-auto flex items-center justify-center text-gray-400">
                  二维码生成中...
                </div>
              </div>

              <!-- 密钥展示 -->
              <div v-else class="secret-container bg-gray-50 border border-dashed border-gray-300 rounded-lg p-4 text-center">
                <p class="secret-tip text-sm text-gray-500 mb-3">请手动输入以下密钥到 Authenticator</p>
                <div class="secret-key-container bg-white border border-gray-200 rounded-md p-3 mb-3">
                  <code class="text-sm font-mono text-gray-800 break-all">{{ formState.secretKey }}</code>
                </div>
                <button
                  type="button"
                  class="text-xs text-blue-600 hover:text-blue-800 underline"
                  @click="copyToClipboard(formState.secretKey)"
                >
                  复制密钥
                </button>
              </div>
            </div>

            <!-- 密码输入 -->
            <FormItem label="密码">
              <Input.Password v-model:value="formState.password" placeholder="请输入密码" size="large" class="w-full" />
            </FormItem>

            <!-- 验证码输入 -->
            <FormItem label="验证码">
              <Input v-model:value="formState.code" placeholder="请输入6位动态验证码" :maxlength="6" size="large" class="w-full"
                @pressEnter="handleLogin" />
            </FormItem>
          </div>

          <!-- 按钮区域 -->
          <FormItem class="action-btn mb-0">
            <!-- 步骤 1：验证按钮 -->
            <Button v-if="step === 1" type="primary" block :loading="loading" size="large"
              class="w-full h-10 font-medium" @click="handleVerifyusername">
              验证账号
            </Button>

            <!-- 步骤 2：登录按钮 -->
            <Space v-if="step === 2" direction="vertical" style="width: 100%" class="space-y-3">
              <Button type="primary" block :loading="loading" size="large" class="w-full h-10 font-medium"
                @click="handleLogin" :disabled="loading">
                登录
              </Button>
              <Button type="link" block @click="handleReset" class="text-sm text-gray-600 hover:text-gray-800" :disabled="loading">
                返回修改账号
              </Button>
            </Space>
          </FormItem>

        </Form>
      </div>
    </div>
    
    <!-- 全屏幕遮罩层 -->
    <div v-if="loading" class="login-loading-overlay">
      <div class="login-loading-content">
        <Spin size="large" tip="登录中..." />
      </div>
    </div>
  </div>
</template>

<style scoped>
.step-content {
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(8px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 优化输入框样式 */
:deep(.ant-input) {
  border-radius: 6px;
}

:deep(.ant-input-affix-wrapper) {
  border-radius: 6px;
}

:deep(.ant-btn-primary) {
  border-radius: 6px;
  transition: all 0.2s ease-in-out;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
  color: #374151;
  margin-bottom: 4px;
}

/* 切换按钮样式 */
.auth-info-container {
  transition: all 0.3s ease;
  position: relative;
}

.qiehuan11{
  position: absolute;
}

.ddd{
  padding: 2px 6px;
}
.ddd1{
  border-top-left-radius: 6px;
}

/* 全屏幕遮罩层样式 */
.login-loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.login-loading-content {
  background-color: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 响应式调整 */
@media (max-width: 640px) {
  .login-wrapper {
    padding-left: 1rem;
    padding-right: 1rem;
  }
}
</style>