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


    <!-- 顶部标题区域 -->
    <view class="header-section">
      <!-- <view class="app-logo">🪶🪶</view> -->
      <image class="app-logo" src="/static/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="/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>

    <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) => {
          const loginParams = {
            code: loginRes.code.trim(), // 必需：微信登录code
            nickname: Logon_Credentials.nickname?.trim() || '', // 可选：用户昵称（从Logon_Credentials获取）
            avatarUrl: Logon_Credentials.active?.trim() || '',  // 可选：用户头像（注意：后端字段是avatarUrl，前端若存的是active，需对应）
            phoneCode: Logon_Credentials.code?.trim() || ''     // 可选：手机号授权code（从Logon_Credentials获取）
          };
          uni.showLoading({title: '登录中...'})
          try {
            // 1. 微信授权登录
            // const wechatLoginResult = await api.auth.wechatLogin(loginParams)
            // ✅ 获取手机号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);

            // 2. 获取手机号
            // const phoneCode = (Logon_Credentials && Logon_Credentials.code && String(Logon_Credentials.code).trim()) ? String(Logon_Credentials.code).trim() : 'mock_dev_code'
            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
            })
          }
        },
        loset(Logon_Credentials) {
          console.log(Logon_Credentials, '登录信息')
          // 获取微信登录code
          uni.login({
            provider: 'weixin',
            success: async (loginRes) => {
              uni.showLoading({title: '登录中...'})
              try {
                // 1. 微信授权登录
                const wechatLoginResult = await api.auth.wechatLogin(loginRes.code)
                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)

                // 2. 获取手机号
                const phoneCode = (Logon_Credentials && Logon_Credentials.code && String(Logon_Credentials.code).trim()) ? String(Logon_Credentials.code).trim() : 'mock_dev_code'
                console.log('📱 使用phoneCode:', phoneCode)

                try {
                  const phoneResult = await api.auth.wechatPhone(phoneCode)
                  const phone = phoneResult?.phone || phoneResult?.data?.phone

                  if (phone) {
                    console.log('✅ 成功获取手机号')
                    user.phone = phone
                  } else {
                    console.warn('⚠️ 手机号为空，使用默认值（开发环境）')
                    // 开发环境：如果后端返回了mock手机号，也可能在user对象中
                    user.phone = user.phone || '13800138000'
                  }
                } catch (phoneError) {
                  console.error('❌ 获取手机号接口失败:', phoneError)
                  // 开发环境容错：继续登录，使用默认手机号
                  user.phone = user.phone || '13800138000'
                  console.warn('⚠️ 使用默认手机号继续登录（开发环境）')
                }

                // 3. 更新用户信息（昵称和头像）
                user.nickname = Logon_Credentials.nickname || user.nickname
                user.avatar = Logon_Credentials.active || user.avatar

                console.log('💾 保存用户信息:', {userId: user.userId, phone: user.phone, nickname: user.nickname})

                // 4. 如果用户输入了昵称或头像，更新到后端
                if (Logon_Credentials.nickname || Logon_Credentials.active) {
                  try {
                    await api.user.updateInfo({
                      userId: user.userId,
                      nickname: user.nickname,
                      avatarUrl: user.avatar
                    })
                    console.log('✅ 用户信息已更新到后端')
                  } catch (updateError) {
                    console.warn('⚠️ 更新用户信息失败:', updateError)
                    // 不影响登录流程，继续
                  }
                }

                // 5. 保存登录信息
                userAuth.saveLoginInfo(token, user)

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

                // 5. 跳转首页
                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>
