<template>
  <div class="login-page">
    <div class="login-left">
      <div>
        <img src="/src/assets/logopc.png" alt="logo" style="height: 24px;"/>
        <p class="titles">豫皖大区</p>
        <p class="titles">西门子家电<span>数据看板</span></p>
        <p class="titles1">YUWAN REGION DATA DASHBOARD FOR SIEMENS HOME APPLIANCES</p>
      </div>
    </div>

    <div class="login-right">
      <div class="login-card">
        <div 
          class="corner-qrcode" 
          @click="tabFlip"
          :style="{ backgroundImage: `url(/src/assets/${tab === 'account' ? 'qrcode.png' : 'macgroup.png'})` }"
        >
        </div>
        <h2 class="title">{{ tab==='account' ? '欢迎登录' : '扫码登录' }}</h2>
        <div v-if="tab==='account'" class="login-form">
          <el-form 
            ref="loginFormRef"
            :model="loginForm" 
            :rules="loginFormRules"
            label-position="left"
          >
            <el-form-item prop="account">
              <el-input
                v-model="loginForm.account"
                placeholder="请输入账号"
                clearable
                maxlength="20"
              >
                <template #prefix>
                  <span class="input-label">账号</span>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                show-password
                clearable
                maxlength="20"
              >
                <template #prefix>
                  <span class="input-label">密码</span>
                </template>
              </el-input>
            </el-form-item>
            <div class="remember-account">
              <el-checkbox v-model="rememberAccount">保持登录</el-checkbox>
            </div>
            
            <el-form-item>
              <el-button 
                type="primary" 
                @click="onLogin" 
                :loading="loginLoading"
                class="login-btn"
                size="large"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div v-if="tab==='scan'">
          <div class="wechat-iframe-container">
            <iframe 
              :src="wechatUrl" 
              class="wechat-iframe"
              frameborder="0"
              allowfullscreen
              sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-top-navigation"
            ></iframe>
          </div>
          <!-- <p class="qr-tip">请在下方页面中完成微信授权登录</p> -->
          <!-- <button class="login-btn" @click="onScanLogin">已授权，确认登录</button> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { apiLogin, apiqrcode,getconfig } from '../api'
import { isLoggedIn, saveLoginData, handleAuthRedirect } from '../utils/auth'
const router = useRouter()
const tab = ref('account')
const loginLoading = ref(false)
const loginForm = ref({
  account: '',
  password: ''
})
const loginFormRef = ref()
const wechatUrl = ref('')

// 登录表单校验规则
const loginFormRules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}
//获取登录背景图
const getBackgroundImage = async () => {
  const res = await getconfig({ code: 'pc_loginbg' })
  if (res.data.value_pull) {
    const loginElement = document.getElementsByClassName('login-page')[0]
    const bannerStr = res.data.value_pull.trim();
    if (bannerStr && loginElement) {
      // 按逗号分隔，过滤空字符串
      loginElement.style.backgroundImage = `url(${bannerStr.split(',').map(url => url.trim()).filter(url => url)[0]})`
    }
  }
}

// 页面加载时检查登录状态
onMounted(() => {
  getBackgroundImage()
  if (isLoggedIn()) {
    ElMessage.info('您已登录，正在跳转到首页...')
    router.replace('/dashboard')
  }
})

async function tabFlip(){
  tab.value = tab.value === 'account' ? 'scan' : 'account'
  if(tab.value === 'scan'){
    try {
      const res = await apiqrcode()
      console.log('微信登录接口返回:', res)
      
      // 直接保存微信登录URL用于iframe
      wechatUrl.value = res.data?.qr_url
      console.log('微信登录URL:', wechatUrl.value)
      
      if (!wechatUrl.value) {
        throw new Error('未获取到微信登录URL')
      }
    } catch (error) {
      console.error('获取微信登录URL失败:', error)
      // 如果接口失败，使用备用URL
      wechatUrl.value = 'https://open.weixin.qq.com/connect/qrconnect?appid=wxfd03df93b36c3728&redirect_uri=https%3A%2F%2Fbsh.yw.hnzhwlkj.cn&response_type=code&scope=snsapi_login&state=backup#wechat_redirect'
    }
  }
}
async function onLogin(){
  // 表单校验
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
  } catch (error) {
    ElMessage.warning('请检查表单信息')
    return
  }
  
  loginLoading.value = true
  try{
    const res = await apiLogin({ 
      account: loginForm.value.account, 
      password: loginForm.value.password 
    })
    if(res && res.data.access_token){
      // 使用工具函数保存登录数据
      saveLoginData(res.data)
      ElMessage.success('登录成功')
      router.push('/dashboard')
    } else {
      ElMessage.error('登录失败')
    }
  } catch(e){
    ElMessage.error(e?.response?.data?.message || '登录失败')
  } finally {
    loginLoading.value = false
  }
}

// 图片加载成功
function onImageLoad() {
  console.log('二维码图片加载成功')
}

// 图片加载失败
function onImageError() {
  console.error('二维码图片加载失败，URL:', qrSrc.value)
  // 如果图片加载失败，尝试使用备用二维码
  if (!qrSrc.value.includes('qrserver.com')) {
    qrSrc.value = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=wechat-login'
  } else {
    // 如果已经是二维码服务但还是失败，尝试重新生成
    console.log('尝试重新生成二维码...')
    tabFlip() // 重新调用获取二维码
  }
}

async function onScanLogin(){
  // simulate qr login success, call login with special username 'scan'
  try{
    const res = await apiLogin({ username: 'scan', password: 'scan' })
    if(res && res.token){
      localStorage.setItem('token', res.token)
      router.push('/dashboard')
    }
  } catch(e){
    alert('扫码登录失败')
  }
}
</script>

<style scoped>
.login-page{
  height:100vh;
  display:flex;
  background: url('/src/assets/Rectangle.png') no-repeat;
  background-size: 100% 100%;
  align-items:center;
  justify-content:center;
}
/* left large image-ish area (you can replace with your image) */
.login-left{
  flex:1;
  margin-left: 10%;
  margin-top: -14%;
  
}
.titles {
  font-size: 44px;
  color: white;
  font-weight: bold;
  margin-top: 30px;
}
.titles span{
    color:#009688 ;
  }
.titles1{
  font-size: 16px;
  color: white;
  margin-top: 30px;
}
/* right card */
.login-right{
  width:600px;
  display:flex;
  align-items:center;
  justify-content:center;
  padding-right:10%;
}
.login-card{
  width:420px;
  background: rgb(0 10 34 / 50%);
  border-radius:12px;
  /* box-shadow: 0 10px 30px rgba(14,42,51,0.08); */
  position:relative;
}
.login-form {
  padding: 20px 28px;
}

.login-form .el-form-item {
  margin-bottom: 20px;
}

.login-form .el-input {
  width: 100%;
  height: 55px;
  font-size: 16px;
}
.input-label{
  color: #333;
}
.corner-qrcode{
  position:absolute;
  width: 50px;
  height: 50px;
  right: -3px;
  top: -3px;
  font-size:12px;
  color:#009688;
  cursor:pointer;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}
/* title */
.title{
  text-align:center;
  margin:60 0 12px;
  font-size:32px;
  color:#fff;
  font-weight:700;
}
/* tabs */
.tabs{ display:flex; gap:10px; justify-content:center; margin-bottom:12px;}
.tabs button{ padding:8px 14px; border-radius:20px; border:none; background:#f3f6f6; cursor:pointer;}
.tabs button.active{ background:#009688; color:#fff; font-weight:600;}

/* form */
.form label{ display:block; margin-top:8px; color:#666; font-size:13px;}
.form input{ width:100%; padding:10px; margin-top:6px; border-radius:6px; border:1px solid #eee; background:#fafafa;}
.login-btn{ width:100%; padding:28px; margin-top:60px; border-radius:30px; border:none; background:#009688; color:#fff; cursor:pointer; font-size:20px;}
.login-btn:hover {
    background-color:#009688;
    border-color: #009688;
    color: #fff;
    outline: none;
}
.form-row {
  display: flex;
  align-items: center;
  margin-top: 14px;
}

.form-row label {
  width: 46px;        /* 固定宽度 */
  font-size: 14px;
  color: #666;
  flex-shrink: 0;
}

.form-row input {
  flex: 1;
  padding: 10px;
  border-radius: 6px;
  border: 1px solid #eee;
  background: #fafafa;
}
/* qr area */
.qr-area{ text-align:center; margin-top:6px;}
.qr-img{ width:160px; height:160px; display:block; margin:12px auto; border-radius:6px; border:1px solid #eee;}
.qr-tip{ color:#777; font-size:13px; margin-bottom:8px;}
.qr-debug{ color:#999; font-size:11px; margin:4px 0; word-break: break-all;}

/* 微信iframe容器 */
.wechat-iframe-container{
  width: 100%;
  max-width: 400px;
  height: 500px;
  padding: 15px;
  margin: 12px auto;
  /* border: 1px solid #e9ecef; */
  /* border-radius: 8px; */
  overflow: hidden;
  /* box-shadow: 0 2px 8px rgba(0,0,0,0.1); */
}
.wechat-iframe{
  width: 100%;
  height: 100%;
  border: none;
  display: block;
}

/* responsive */
@media (max-width: 768px){
  .login-page{ align-items:flex-start; padding-top:40px; }
  .login-left{ display:none; }
  .login-right{ width:100%; padding:0 16px; margin:0 auto; }
  .login-card{ width:100%; padding:18px; border-radius:10px; }
  .qr-img{ width:120px; height:120px; }
  .wechat-iframe-container{
    max-width: 100%;
    height: 400px;
  }
}
:deep(.el-checkbox__label) {
  color: #fff;
}
</style>
