<template>
  <div class="safe-verify-container">
    <div class="verify-card">
      <h2>安全验证</h2>
      <p>您正在执行敏感操作，需要进行二次验证</p>

      <div class="verify-content">
        <second-verify
          v-model:visible="verifyVisible"
          :user-info="userInfo"
          :title="'安全验证'"
          :operation-type="'safe'"
          @verify-success="handleVerifySuccess"
          @verify-cancel="handleVerifyCancel"
        >
        </second-verify>
      </div>

      <div class="actions">
        <el-button type="primary" @click="goBack">返回</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getUserProfile } from '@/api/system/user';
import { UserVO } from '@/api/system/user/types';
import cache from '@/plugins/cache';
import SecondVerify from '@/views/system/user/secondVerify.vue';
import { secureRandom } from '@/utils/ruoyi';

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

// 用户信息
const userInfo = reactive<Partial<UserVO>>({});
// 验证组件可见性
const verifyVisible = ref(true);
// 原始请求路径
const redirectPath = ref('');

// 获取当前用户信息
const loadUserInfo = async () => {
  try {
    const res = await getUserProfile();
    Object.assign(userInfo, res.data.user);
  } catch (error) {
    ElMessage.error('获取用户信息失败');
  }
};

// 验证成功回调
const handleVerifySuccess = async (result: any) => {
  if (result.success) {
    // 生成安全令牌并缓存
    const safeToken = Date.now().toString(36) + secureRandom().toString(36).substring(2);
    cache.local.set('safeToken', safeToken, 60 * 10); // 10分钟有效期

    try {
      // 重试原始安全请求
      ElMessage.success('操作已完成');
      // 跳转回原始页面
      const redirect = (route.query.redirect as string) || '/';
      router.replace(redirect);
    } catch (error) {
      ElMessage.error('操作失败，请重试');
    }
  }
};

// 验证取消回调
const handleVerifyCancel = () => {
  goBack();
};

// 返回原始页面
const goBack = () => {
  const redirect = decodeURIComponent((route.query.redirect as string) || '/');
  redirectPath.value = redirect.split('?')[0] || '/';
  router.replace(redirectPath.value);
};

onMounted(() => {
  loadUserInfo();
});
</script>

<style scoped>
.safe-verify-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 70vh;
  padding: 20px;
}

.verify-card {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 600px;
  text-align: center;
}

h2 {
  margin-bottom: 20px;
  color: #333;
}

p {
  margin-bottom: 30px;
  color: #666;
}

.verify-content {
  margin-bottom: 30px;
}

.actions {
  display: flex;
  justify-content: center;
}
</style>
