<template>
  <div class="loginView">

    <!-- 背景 -->
    <div class="login-bg"></div>

    <div class="login-wrapper">

      <div class="login-card">

        <!-- 左侧品牌 -->
        <div class="brand-panel">

          <h1 class="brand-title">XSynergy</h1>

          <h3 class="brand-sub">
            企业级 AR 远程协作管理平台
          </h3>

          <p class="brand-desc">
            通过实时音视频、增强现实标注与人工智能技术，
            实现现场人员与远程专家沉浸式协作，
            打破地理限制，提高企业协作效率。
          </p>

          <div class="feature-list">

            <div class="feature-item">AR远程协作</div>
            <div class="feature-item">实时音视频</div>
            <div class="feature-item">AI智能辅助</div>
            <div class="feature-item">协作记录管理</div>

          </div>

        </div>

        <!-- 右侧登录 -->
        <div class="login-panel">

          <h2 class="login-title">系统登录</h2>

          <el-form ref="loginRef" class="login-form" :model="loginForm" :rules="loginRules">

            <el-form-item prop="username">
              <el-input v-model="loginForm.username" placeholder="请输入账号" size="large" />
            </el-form-item>

            <el-form-item prop="password">
              <el-input 
                v-model="loginForm.password" 
                :type="showPassword ? 'text' : 'password'" 
                placeholder="请输入密码" 
                size="large"
                @keyup.enter="handleLogin"
              >
                <template #suffix>
                  <el-icon class="password-eye" @click="togglePasswordVisibility">
                    <component :is="showPassword ? View : Hide" />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-button :loading="loading" class="login-button" type="primary" size="large"
                @click.prevent="handleLogin">
                <span v-if="!loading">登 录</span>
                <span v-else>登录中...</span>
              </el-button>
            </el-form-item>

          </el-form>

        </div>

      </div>

    </div>

  </div>
</template>

<script setup>
import { useUserStore } from '@/stores/modules/user.js'
import { watch, ref, getCurrentInstance, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElNotification, ElMessage } from 'element-plus'
import { View, Hide } from '@element-plus/icons-vue'
import CryptoJS from 'crypto-js';
import { useMeterStore } from '@/stores/modules/meter'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()

const meterStore = useMeterStore()


const redirect = ref(undefined);
const loginView = ref(true)

// 监听路由变化，获取重定向参数
watch(() => route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });

const loginForm = ref({
  username: '',
  password: '',
})

const loginRules = {
  username: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
  password: [{ required: true, trigger: 'blur', message: '请输入密码' }],
}

const loading = ref(false)

// 密码显示状态
const showPassword = ref(false)

// 切换密码可见性
function togglePasswordVisibility() {
  showPassword.value = !showPassword.value
}


function handleLogin() {
  proxy.$refs.loginRef.validate((valid) => {
    if (valid) {
      loading.value = true
      meterStore.initUdid()
      if (!localStorage?.getItem('UDID')) {
        ElMessage({
          message: '服务错误，请刷新页面',
          type: 'warning',
        })
        return
      }
      const secretKey = ((loginForm.value.username + localStorage?.getItem('UDID')).toLowerCase()).replaceAll('-', ''); // 用户名+UDID(32位16进制，全小写)
      const randomChars = generateRandomChars(6);
      const message = `Gx${randomChars}${loginForm.value.password}`;
      const ciphertext = CryptoJS.Blowfish.encrypt(message, secretKey).toString();
      // 调用action的登录方法 
      userStore
        .login({
          // password: loginForm.value.password,
          password: ciphertext,
          username: loginForm.value.username,
        })
        .then(async (res) => {
          const userInfo = JSON.parse(sessionStorage.getItem('userData'))
          await handleLoginSuccess();
        })
        .catch((e) => {
          console.log('登录失败', e)
          loading.value = false
        })
    }
  })
  requestNotificationPermission()
}

/**
 * 处理登录成功后的跳转逻辑
 */
async function handleLoginSuccess() {
  try {
    // 如果有重定向路径且不是登录页，则跳转到重定向页面
    if (redirect.value && redirect.value !== '/login') {

      // 确保路由存在，如果不存在则跳转到默认页面
      try {
        // 解析路径，检查是否是有效路由
        const resolved = router.resolve(redirect.value);
        if (resolved.matched.length > 0) {
          await router.push(redirect.value);
        } else {
          console.warn('重定向路径无效，跳转到默认页面');
          await router.push('/userManagement');
        }
      } catch (error) {
        console.warn('重定向跳转失败，跳转到默认页面:', error);
        await router.push('/userManagement');
      }
    } else {
      // 没有重定向或重定向到登录页，跳转到默认页面 
      await router.push('/userManagement');
    }
  } catch (error) {
    console.error('登录跳转异常:', error);
    // 降级处理：跳转到默认页面 
    await router.push('/userManagement');
  } finally {
    loading.value = false;
  }
}

// 生成随机字符串
function generateRandomChars(length) {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

/**
 * @description 请求浏览器的通知权限
 * @returns {*}
 */
function requestNotificationPermission() {
  if ('Notification' in window) {
    Notification.requestPermission().then(() => { })
  } else {
    console.log('浏览器不支持通知')
  }
}


onMounted(async () => {
  // meterStore.initUdid()
});

</script>

<style lang="scss" scoped>
.loginView {
  width: 100vw;
  height: 100vh;
  position: relative;
  overflow: hidden;
}

/* 背景 */

.login-bg {
  position: absolute;
  inset: 0;

  background:
    radial-gradient(circle at 20% 20%, rgba(64, 158, 255, .15), transparent 40%),
    radial-gradient(circle at 80% 80%, rgba(64, 158, 255, .15), transparent 40%),
    linear-gradient(120deg, #f6f9fc, #eef3ff);
}

/* 动态光效 */

.login-bg::after {
  content: "";
  position: absolute;

  width: 600px;
  height: 600px;

  background: radial-gradient(circle,
      rgba(64, 158, 255, .25),
      transparent 70%);

  filter: blur(80px);

  animation: floatLight 12s infinite alternate;
}

@keyframes floatLight {

  from {
    transform: translate(-200px, -100px);
  }

  to {
    transform: translate(300px, 200px);
  }

}

/* 居中容器 */

.login-wrapper {
  position: relative;
  z-index: 2;

  width: 100%;
  height: 100%;

  display: flex;
  align-items: center;
  justify-content: center;
}

/* 主卡片 */

.login-card {

  width: 960px;
  height: 520px;

  display: flex;

  border-radius: 16px;

  background: rgba(255, 255, 255, .9);

  backdrop-filter: blur(10px);

  box-shadow:
    0 20px 50px rgba(0, 0, 0, .08);

  overflow: hidden;
}

/* 左侧品牌 */

.brand-panel {

  flex: 1;

  padding: 60px;

  display: flex;
  flex-direction: column;
  justify-content: center;
}

.brand-title {
  font-size: 40px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 10px;
}

.brand-sub {
  color: #409EFF;
  margin-bottom: 25px;
}

.brand-desc {
  color: #606266;
  line-height: 1.7;
  margin-bottom: 30px;
}

.feature-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 14px;
}

.feature-item {

  padding: 10px 14px;

  border-radius: 6px;

  background: #f5f7fa;

  border: 1px solid #ebeef5;

  transition: all .25s;
}

.feature-item:hover {
  border-color: #409EFF;
  color: #409EFF;
}

/* 右侧登录 */

.login-panel {

  width: 380px;

  padding: 60px 40px;

  border-left: 1px solid #ebeef5;

  display: flex;
  flex-direction: column;
  justify-content: center;
}

.login-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 30px;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
  height: 44px;
}

/* 密码查看图标样式 */
.password-eye {
  cursor: pointer;
  color: #909399;
  transition: color 0.2s;
}

.password-eye:hover {
  color: #409EFF;
}

/* 登录按钮 */

.login-button {

  width: 100%;

  height: 44px;

  border-radius: 6px;

  background: linear-gradient(135deg,
      #409EFF,
      #66b1ff);

  border: none;
}

.login-button:hover {

  transform: translateY(-1px);

  box-shadow: 0 6px 16px rgba(64, 158, 255, .25);
}

/* 移动端 */

@media screen and (max-width: 900px) {

  .login-card {

    flex-direction: column;

    width: 90%;

    height: auto;
  }

  .login-panel {

    width: 100%;

    border-left: none;

    border-top: 1px solid #eee;
  }

}
</style>