<template>
  <div class="login-container" :class="{ 'mobile-view': isMobile }">
    <div class="login-content">
      <div class="login-image-section">
        <div class="login-image"></div>
      </div>
      <div class="login-form-section">
        <div class="login-box">
          <div class="logo">
            <img class="logo-img" alt="格莱默打印系统" src="../../assets/imgs/logo.png" />
            <h2>格莱默打印系统</h2>
          </div>
          <!--      <p class="warning-text">禁止转借个人或他人账号</p>-->

          <div v-if="currentRouteName == 'Login'">
            <div v-if="isMobile">
              <LoginForm class="m-auto h-auto lt-xl:(rounded-3xl light:bg-white)" />
            </div>
            <div v-else>
              <LoginForm class="m-auto h-auto lt-xl:(rounded-3xl light:bg-white)" />
              <!-- <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="账号登录" name="first">
                  <LoginForm class="m-auto h-auto lt-xl:(rounded-3xl light:bg-white)" />
                </el-tab-pane>
                <el-tab-pane label="飞书扫码" name="second">
                  <div class="qr_box">
                    <div id="login_container"></div>
                  </div>
                </el-tab-pane>
              </el-tabs> -->
            </div>
          </div>

          <div v-if="currentRouteName == 'SSOLogin'"
            ><SSOLoginVue class="m-auto h-auto p-20px lt-xl:(rounded-3xl light:bg-white)"
          /></div>

          <Transition appear enter-active-class="animate__animated animate__bounceInRight">
            <div
              class="m-auto h-[calc(100%-60px)] w-[100%] flex items-center at-2xl:max-w-500px at-lg:max-w-500px at-md:max-w-500px at-xl:max-w-500px"
            >
              <!-- 账号登录 -->
              <!-- <LoginForm class="m-auto h-auto p-20px lt-xl:(rounded-3xl light:bg-white)" /> -->
              <!-- 手机登录 -->
              <!-- <MobileForm class="m-auto h-auto p-20px lt-xl:(rounded-3xl light:bg-white)" /> -->
              <!-- 二维码登录 -->
              <!-- <QrCodeForm class="m-auto h-auto p-20px lt-xl:(rounded-3xl light:bg-white)" /> -->
              <!-- 注册 -->
              <!-- <RegisterForm class="m-auto h-auto p-20px lt-xl:(rounded-3xl light:bg-white)" /> -->
              <!-- 三方登录 -->
              <!-- <SSOLoginVue class="m-auto h-auto p-20px lt-xl:(rounded-3xl light:bg-white)" /> -->
              <!-- 忘记密码 -->
              <!-- <ForgetPasswordForm class="m-auto h-auto p-20px lt-xl:(rounded-3xl light:bg-white)" /> -->
            </div>
          </Transition>
          <!-- 飞书扫码登录 -->
          <!-- <div v-if="activeTab === 'scan'" class="scan-login">
            <p>请使用飞书扫描二维码登录</p>
            <div class="qr-code-placeholder"></div>
          </div> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as authUtil from '@/utils/auth'
import * as LoginApi from '@/api/login'
import { LoginForm } from './components'
import { SSOLoginVue } from './components'
const activeTab = ref('account')
const rememberMe = ref(false)
const isMobile = ref(false)
const activeName = ref('first')
const QRLoginObj = ref()
const redirectUri1 = import.meta.env.VITE_REDIRECT_URI || ''
// const FEISHU_APP_ID_KEY = import.meta.env.VITE_FEISHU_APP_ID || ''
const tenantName = import.meta.env.VITE_APP_DEFAULT_LOGIN_TENANT || ''
const { currentRoute } = useRouter() // 路由
const currentRouteName = ref()
const redirect = ref('')
const loading = ref() // ElLoading.service 返回的实例
//src\components\Verifition\src\Verify\VerifySlide.vue
const router = useRouter()

const handleClick = (tab, event) => {
  // console.log(tab, event, tab.props.label)
  if (tab.props.label === '飞书扫码') {
    getQRLogin()
  } else {
    if (QRLoginObj.value) {
      const container = document.getElementById('login_container')
      if (container) container.innerHTML = ''
      QRLoginObj.value = null
    }
  }
}
// const REDIRECT_URI = redirectUri1 // 替换为你的前端页面地址（需与飞书平台配置一致）
// const FEISHU_APP_ID = FEISHU_APP_ID_KEY // 替换为你的前端页面地址（需与飞书平台配置一致）
// const goto = `https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=${FEISHU_APP_ID}&redirect_uri=${REDIRECT_URI}&response_type=code&state=STATE`
//https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=cli_a834fd65ed3e100e&redirect_uri=http://122.152.216.7/business-platform-test&response_type=code&state=STATE
const getQRLogin = () => {
  // console.log('QRLogin', QRLogin)
  QRLoginObj.value = QRLogin({
    id: 'login_container', // 二维码容器元素ID
    goto: goto,
    width: '400', // 二维码宽度
    height: '400', // 二维码高度
    style: 'width:400px;height:300px;border: none; background: transparent;' // 可选样式
  })
}

// 响应式检测
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}
// 获取租户 ID
const getTenantId = async () => {
  const res = await LoginApi.getTenantIdByName(tenantName)
  authUtil.setTenantId(res)
}
const toLogin = async (code) => {
  try {
    let redirectUri = redirectUri1
    await getTenantId()
    const res = await LoginApi.feishuLogin({ code, redirectUri })
    console.log(res)
    if (!res) {
      return
    }
    loading.value = ElLoading.service({
      lock: true,
      text: '正在加载系统中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    // if (loginDataLoginForm.rememberMe) {
    //   authUtil.setLoginForm(loginDataLoginForm)
    // } else {
    //   authUtil.removeLoginForm()
    // }
    authUtil.setToken(res)
    if (!redirect.value) {
      redirect.value = '/'
    }
    // 判断是否为SSO登录
    if (redirect.value.indexOf('sso') !== -1) {
      window.location.href = window.location.href.replace('/login?redirect=', '')
    } else {
      // await push({ path: redirect.value || permissionStore.addRouters[0].path })
      // 登录成功后跳转到指定的SSO主页
      console.log('111110000111')

      await router.push({ path: '/' })
    }
  } finally {
    loading.value.close()
  }
}
const handleMessage = (event) => {
  console.log(666666, event)
  // alert(JSON.stringify(event.data))
  // 验证消息来源和数据合法性
  if (
    QRLoginObj.value &&
    QRLoginObj.value.matchOrigin(event.origin) &&
    QRLoginObj.value.matchData(event.data)
  ) {
    const loginTmpCode = event.data.tmp_code
    // console.log(123456, `${goto}&tmp_code=${loginTmpCode}`)
    // debugger
    window.location.href = `${goto}&tmp_code=${loginTmpCode}`
    // 拼接 tmp_code 并重定向
    //window.location.href = `${goto}&tmp_code=${loginTmpCode}`
  }
}

// 添加事件监听
// if (typeof window.addEventListener != 'undefined') {
//     window.addEventListener('message', handleMessage, false);
// } else if (typeof window.attachEvent != 'undefined') {
//     window.attachEvent('onmessage', handleMessage);
// }

onMounted(() => {
  const url = window.location.href
  const codeMatch = url.match(/[?&]code=([^&]+)/) // 匹配 ?code=xxx 或 &code=xxx
  const codeValue = codeMatch ? codeMatch[1] : null
  console.log(url)

  console.log('Code value999:', codeValue, url.indexOf('/sso') == -1) // "0wWiB3b3zA66AbFJF8Adw7x3FA0dH0Cy"

  // const hasCode = new URLSearchParams(window.location.search).has('code')
  // console.log('code', hasCode)
  // if (codeValue) {

  //   toLogin(codeValue) // 处理回调逻辑
  // }
  if (codeValue && url.indexOf('/sso') == -1) {
    console.log('1111111111111111111111001')

    toLogin(codeValue) // 处理回调逻辑
  }

  checkMobile()
  window.addEventListener('resize', checkMobile)
  // 飞书添加事件监听
  window.addEventListener('message', handleMessage, false)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', checkMobile)
  if (QRLoginObj.value) {
    const container = document.getElementById('login_container')
    if (container) container.innerHTML = ''
    QRLoginObj.value = null
  }
})
watch(
  () => currentRoute.value,
  (route) => {
    currentRouteName.value = route.name
    console.log(999999, route.name)

    // if (route.name === 'SSOLogin') {
    //   currentRouteName.value = route.name
    //   // setLoginState(LoginStateEnum.SSO)
    //   // init()
    // }
  },
  { immediate: true }
)
</script>

<style scoped>
/* 移动端优化 */
@media (width <= 768px) {
  .login-container {
    padding: 10px;
    background: white;
  }

  .login-content {
    height: auto;
    max-width: 100%;
    border-radius: 0;
    box-shadow: none;
    flex-direction: column;
  }

  .login-image-section {
    display: none;
  }

  .login-form-section {
    width: 100% !important;
    min-height: 100vh;
    padding: 20px;
    background: white;
  }

  .login-box {
    width: 100% !important;
    height: auto;
    max-width: 100%;
    padding: 20px;
    margin: 0;
  }

  .logo {
    margin-bottom: 30px;
  }

  .logo-img {
    width: 68px;
  }

  .logo h2 {
    font-size: 24px;
  }

  .login-tabs span {
    font-size: 14px;
  }
}

/* 平板端优化 */
@media (width > 768px) and (width <= 1024px) {
  .login-content {
    height: 500px;
    max-width: 900px;
  }

  .login-form-section {
    padding: 30px;
  }

  .login-box {
    max-width: 400px;
    padding: 30px;
  }

  .logo h2 {
    font-size: 26px;
  }
}

.login-container {
  display: flex;
  min-height: 100vh;
  padding: 20px;
  background: #f5f7fa;
  justify-content: center;
  align-items: center;
}

.login-content {
  display: flex;
  width: 100%;
  height: 500px;
  max-width: 1100px;
  overflow: hidden;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgb(0 0 0 / 10%);
}

.login-image-section {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.login-image {
  width: 100%;
  height: 100%;
  background: url('@/assets/imgs/login/login-img.png') no-repeat center center;
  background-size: cover;
}

.login-form-section {
  display: flex;
  width: 45%;
  padding: 30px;
  align-items: center;
  justify-content: center;
}

.login-box {
  width: 100%;
  max-width: 450px;
  padding: 40px;
  background: transparent;
}

/* Logo样式 */
.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.logo-img {
  width: 88px;
  margin-right: 10px;
}

.logo h2 {
  margin: 0;
  font-family: 'Microsoft YaHei UI';
  font-size: 28px;
  font-style: bold;
  font-weight: 700;
  line-height: 100%;
  letter-spacing: 0%;
  color: #333;
}

/* 警告文本 */
.warning-text {
  margin-bottom: 30px;
  font-family: 'Microsoft YaHei UI';
  font-size: 20px;
  font-style: regular;
  font-weight: 400;
  line-height: 100%;
  letter-spacing: 0%;
  color: rgb(96 108 144 / 60%);
  text-align: center;
}

/* Tab切换 */
.login-tabs {
  display: flex;
  margin-bottom: 20px;
}

.login-tabs span {
  padding: 8px 0;
  font-family: 'Microsoft YaHei UI';
  font-size: 20px;
  font-style: regular;
  font-weight: 400;
  color: #666;
  text-align: center;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  flex: 1;

  /* line-height: 100%;
  letter-spacing: 0%; */
}

.login-tabs span.active {
  font-style: bold;
  font-weight: 700;
  color: #333;
  border-bottom-color: #0118a3;

  /* line-height: 100%;
  letter-spacing: 0%; */

  /* border: 2px solid #0118A3 */
}

/* 表单样式 */
.verify-code-input {
  display: flex;
  align-items: center;
  gap: 10px;
}

.verify-code {
  width: 80px;
  padding: 8px;
  font-weight: bold;
  text-align: center;
  background: #f5f7fa;
  border-radius: 4px;
  flex-shrink: 0;
}

.remember-me {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.forgot-password {
  font-size: 12px;
  color: #409eff;
  text-decoration: none;
}

.login-button {
  width: 100%;
}

/* 扫码登录样式 */
.qr-code-placeholder {
  display: flex;
  height: 200px;
  margin-top: 20px;
  color: #999;
  background: #f5f7fa;
  border-radius: 4px;
  align-items: center;
  justify-content: center;
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  font-size: 32px;
  font-weight: 600;
  color: #6b778c;
}

/* 改变文字颜色和下划线距离 */
:deep(.el-tabs__item) {
  padding-bottom: 20px;
  margin-top: 10px;
  font-size: 24px;
  font-weight: 500;
  color: #666;
}

/* 改变下划线背景色 */
:deep(.el-tabs__nav-wrap::after) {
  /* background-color: #0c314d; */
}

/* 改变选择后的文字颜色 */
:deep(.el-tabs__item.is-active) {
  font-style: bold;
  font-weight: 700;
  color: #333;
  opacity: 1;
}

/* 改变选择的下划线颜色  */

/* 下划线颜色 */
:deep(.el-tabs__active-bar) {
  background-color: #0118a3;

  /* border: 2px solid #0118A3 */
}

.qr_box {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 基础样式 */
</style>
