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

    <!-- 顶部标题区域 -->
    <view class="header-section">
      <image class="app-logo" src="/static/logo.png" mode="widthFix"></image>
      <view class="app-slogan">真诚相遇 · 携手一生</view>
    </view>

    <!-- 登录框 -->
    <view class="login-box">
      <button class="wechat-login-btn" @click="login_zheshow">
        <image class="wechat-icon" src="/static/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>

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

<script>
import butlogin from '@/components/butlogin'
import api from '@/utils/api.js'
import userAuth from '@/utils/userAuth.js'
import timManager from '@/utils/tim-manager.js'
import timPresenceManager from '@/utils/tim-presence-manager.js'

export default {
  components: {
    butlogin
  },
  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) => {
          const loginParams = {
            code: loginRes.code.trim(), // 必需：微信登录code
            nickname: Logon_Credentials.nickname?.trim() || '', // 可选：用户昵称
            avatarUrl: Logon_Credentials.active?.trim() || '',  // 可选：用户头像
            phoneCode: Logon_Credentials.code?.trim() || ''     // 可选：手机号授权code
          };
          uni.showLoading({ title: '登录中...' })
          try {
            // ✅ 获取手机号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('用户昵称:', Logon_Credentials.nickname)
            console.log('用户头像:', Logon_Credentials.active ? '已提供' : '未提供')
            console.log('手机号code:', phoneCode || '未提供')

            // ✅ 一次性调用微信登录接口，传入所有信息
            const wechatLoginResult = await api.auth.wechatLogin({
              code: loginRes.code,
              nickname: Logon_Credentials.nickname || '微信用户',
              avatarUrl: Logon_Credentials.active || null,
              phoneCode: phoneCode
            });

            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)
            uni.setStorageSync("userId", user.userId);

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

            // ✅ 保存登录信息（后端已返回完整信息，直接保存）
            userAuth.saveLoginInfo(token, user)
            
            uni.hideLoading()
            uni.showToast({ title: '登录成功', icon: 'success' })
            
            // ✅ 跳转首页
            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;
  }

  .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: 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>