<template>
  <view class="content">
    <!-- 背景图片 -->
    <image class="bg-image" src="http://115.190.125.125:9000/static-images/login-bg.png" mode="aspectFill"></image>


    <!-- 顶部标题区域 -->
    <view class="header-section">
      <!-- <view class="app-logo">🪶🪶</view> -->
      <image class="app-logo" src="http://115.190.125.125:9000/static-images/logo.png" mode="widthFix"></image>
      <!-- <view class="app-name">青鸾之恋</view> -->
      <view class="app-slogan">真诚相遇 · 携手一生</view>
    </view>

    <!-- 登录框 -->
    <view class="login-box">
      <!-- 微信一键登录 -->
      <button class="wechat-login-btn" @click="login_zheshow">
        <image class="wechat-icon" src="http://115.190.125.125:9000/static-images/wechat-icon.png" mode="aspectFit"></image>
        <text>微信一键登录</text>
      </button>

    </view>

    <!-- 底部提示 -->
    <view class="footer-tip">
      <text class="tip-icon">💗</text>
      <text class="tip-text">遇见对的人，不再孤单</text>
    </view>

    <btnlogin :zheshow='zheshow'/>
  </view>
</template>

<script>
import btnlogin from '@/components/butlogin';
import api from '@/utils/api.js'
import userAuth from '@/utils/userAuth.js'

export default {
  components: {
    btnlogin
  },
  data() {
    return {
      zheshow: false, // 控制弹窗显示隐藏
      redirectUrl: '' // 登录成功后跳转地址（可选）
    }
  },

  onLoad(options) {
    // 处理跳转参数
    this.redirectUrl = options && options.redirect ? decodeURIComponent(options.redirect) : ''
  },

  methods: {
    login_zheshow() {
      this.zheshow = !this.zheshow
    },
    loset(Logon_Credentials) {
      console.log('=== 开始微信登录流程 ===')
      console.log('用户登录信息:', Logon_Credentials)

      // 获取微信登录code
      uni.login({
        provider: 'weixin',
        success: async (loginRes) => {
          // ✅ 获取手机号code
          const phoneCode = (Logon_Credentials && Logon_Credentials.code && String(Logon_Credentials.code).trim())
              ? String(Logon_Credentials.code).trim()
              : null;

          console.log('微信登录code:', loginRes.code)
          console.log('手机号code:', phoneCode || '未提供')

          // ✅ 一次性调用微信登录接口，无需用户提供头像和昵称
          const loginParams = {
            code: loginRes.code,
            phoneCode: phoneCode
          };
          
          uni.showLoading({title: '登录中...'})
          try {
            const wechatLoginResult = await api.auth.wechatLogin(loginParams);

            const token = wechatLoginResult?.token || wechatLoginResult?.data?.token
            const user = wechatLoginResult?.user || wechatLoginResult?.data?.user

            if (!token || !user) {
              throw new Error('微信登录返回数据异常')
            }

            console.log('✅ 微信登录成功，用户ID:', user.userId)
            console.log('✅ 微信登录成功')
            console.log('用户ID:', user.userId)
            console.log('昵称:', user.nickname)
            console.log('头像:', user.avatarUrl ? '已设置' : '未设置')
            console.log('手机号:', user.phone || '未设置')
            
            uni.setStorageSync("userId", user.userId);

            // ✅ 保存登录信息（后端已返回完整信息，直接保存）
            userAuth.saveLoginInfo(token, user)

            uni.hideLoading()
            uni.showToast({title: '登录成功', icon: 'success'})

            // ✅ 初始化 TIM 和 WebSocket
            console.log('🚀 登录成功，开始初始化 TIM 和 WebSocket...')
            
            // 延迟一下，确保全局方法已挂载
            await new Promise(resolve => setTimeout(resolve, 200))
            
            try {
              const app = getApp()
              if (app && app.globalData && app.globalData.initGlobalTIM) {
                await app.globalData.initGlobalTIM()
                console.log('✅ TIM 和 WebSocket 初始化完成')
              } else {
                console.warn('⚠️ 全局 initGlobalTIM 方法不存在，尝试直接导入')
                // 如果全局方法不存在，直接导入 tim-manager
                const timManager = require('@/utils/tim-manager.js').default
                const timPresenceManager = require('@/utils/tim-presence-manager.js').default
                
                // 初始化 TIM
                if (!timManager.isLogin) {
                  const SDKAppID = 1600109674
                  if (!timManager.tim) {
                    timManager.init(SDKAppID)
                    console.log('✅ TIM SDK 初始化完成')
                  }
                  
                  const res = await uni.request({
                    url: `http://localhost:8083/api/im/getUserSig?userId=${user.userId}`,
                    method: 'GET'
                  })
                  
                  if (res[1].data.code === 200) {
                    const userSig = res[1].data.data.userSig
                    await timManager.login(String(user.userId), userSig)
                    console.log('✅ TIM 登录成功')
                    
                    // 初始化 WebSocket
                    await timPresenceManager.init(String(user.userId))
                    console.log('✅ WebSocket 初始化完成')
                  }
                }
              }
            } catch (error) {
              console.error('❌ 初始化 TIM 失败:', error)
            }

            // ✅ 跳转首页
            setTimeout(() => {
              const target = this.redirectUrl || '/pages/index/index'
              uni.reLaunch({url: target})
            }, 500)
          } catch (error) {
            console.error('❌ 微信登录失败:', error)
            uni.hideLoading()
            uni.showToast({
              title: error?.message || '登录失败，请重试',
              icon: 'none',
              duration: 2000
            })
          }
        },
        fail: (err) => {
          console.error('获取微信code失败:', err)
          uni.showToast({title: '微信登录失败', icon: 'none'})
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  padding: 40rpx;
  min-height: 100vh;
  position: relative;
  overflow: hidden;

  .bg-image {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    pointer-events: none;
  }

  // 添加装饰性元素
  &::before {
    content: '❤️';
    position: absolute;
    top: 100rpx;
    right: 60rpx;
    font-size: 60rpx;
    opacity: 0.2;
    animation: heartbeat 2s infinite;
  }

  &::after {
    content: '💕';
    position: absolute;
    bottom: 200rpx;
    left: 40rpx;
    font-size: 50rpx;
    opacity: 0.2;
    animation: heartbeat 2s infinite 0.5s;
  }
}

@keyframes heartbeat {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

.header-section {
  text-align: center;
  margin-bottom: 60rpx;
  position: relative;
  z-index: 1;

  .app-logo {
    font-size: 120rpx;
    margin-bottom: 20rpx;
    // animation: heartbeat 1s infinite;
  }

  .app-name {
    font-size: 48rpx;
    font-weight: bold;
    background: linear-gradient(135deg, #ff6b9d 0%, #ff8fab 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    margin-bottom: 15rpx;
  }

  .app-slogan {
    font-size: 26rpx;
    color: #333333;
    opacity: 0.8;
  }
}

.login-box {
  background: rgba(211, 127, 140, 0);
  border-radius: 30rpx;
  padding: 80rpx 40rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 8rpx 24rpx rgba(255, 107, 157, 0.15);
  border: 2rpx solid rgba(255, 107, 157, 0.1);
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  z-index: 1;

  // 	.wechat-login-btn {
  // 	width: 100%;
  // 	height: 90rpx;
  // 		background: #FFFFFF;
  // 		color: #ff6b9d;
  // 	border-radius: 50rpx;
  // 	font-size: 30rpx;
  // 	font-weight: bold;
  // 	display: flex;
  // 	align-items: center;
  // 	justify-content: center;
  // 		border: 2rpx solid #ff6b9d;
  // 		box-shadow: 0 8rpx 20rpx rgba(255, 107, 157, 0.2);

  // 	.wechat-icon {
  // 		width: 40rpx;
  // 		height: 40rpx;
  // 		margin-right: 10rpx;
  // 	}

  // 	&:active {
  // 		opacity: 0.9;
  // 		transform: translateY(2rpx);
  // 	}
  // }
  .wechat-login-btn {
    width: 100%;
    height: 96rpx;
    // 渐变背景+光泽叠加
    background: linear-gradient(90deg, #9d40e9 0%, #5a35f7 100%),
    radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.15), transparent 50%);
    background-blend-mode: overlay;
    color: #ffffff;
    border-radius: 60rpx;
    font-size: 32rpx;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    // 多层光影：外层投影+内高光+内阴影
    box-shadow: 0 6rpx 16rpx rgba(90, 53, 247, 0.4),
    0 3rpx 8rpx rgba(90, 53, 247, 0.2),
    inset 0 2rpx 3rpx rgba(255, 255, 255, 0.25),
    inset 0 -2rpx 3rpx rgba(0, 0, 0, 0.15);
    transition: all 0.2s ease; // 动画过渡，更自然
  }

  .wechat-login-btn:active {
    transform: translateY(2rpx);
    box-shadow: 0 3rpx 8rpx rgba(90, 53, 247, 0.3),
    0 1rpx 4rpx rgba(90, 53, 247, 0.2),
    inset 0 1rpx 2rpx rgba(255, 255, 255, 0.15),
    inset 0 -2rpx 3rpx rgba(0, 0, 0, 0.2);
  }

  .wechat-icon {
    width: 45rpx;
    height: 45rpx;
    margin-right: 15rpx;
    filter: drop-shadow(0 1rpx 2rpx rgba(0, 0, 0, 0.1)); // 给图标加轻微阴影，更立体
  }
}

.footer-tip {
  text-align: center;
  margin-top: 60rpx;
  padding: 30rpx;
  position: relative;
  z-index: 1;

  .tip-icon {
    font-size: 50rpx;
    display: block;
    margin-bottom: 15rpx;
    animation: heartbeat 2s infinite;
  }

  .tip-text {
    font-size: 26rpx;
    color: #333333;
    font-weight: 500;
    letter-spacing: 2rpx;
  }
}

button {
  &::after {
    border: none;
  }
}
</style>
