<template>
  <view class="login-container">
    <view class="login-box">
      <!-- Logo区域 -->
      <view class="logo-area">
        <image class="logo" src="/static/login.png" mode="aspectFit"></image>
        <text class="title">小鹅通</text>
        <text class="slogan">让知识分享更简单</text>
      </view>

      <!-- 登录方式区域 -->
      <view class="login-methods">

        <!-- 微信登录按钮 -->
        <button class="login-btn wechat" @click="handleWechatLogin">
          <text class="iconfont icon-wechat"></text>
          微信一键登录
        </button>

        <!-- 其他登录方式 -->
        <view class="other-login">
          <text class="divider">其他登录方式</text>
          <view class="login-options">
            <view class="option" @click="navigateToVerifyCodeLogin">
              <text class="iconfont icon-verify"></text>
              <text>手机号码登录</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 协议区域 -->
      <view class="agreement">
        <checkbox-group @change="handleAgreementChange">
          <label class="agreement-label">
            <checkbox :checked="isAgreed" color="#007AFF" />
            <text class="agreement-text">
              我已阅读并同意
              <text class="link" @click="openServiceAgreement">《服务协议》</text>
              和
              <text class="link" @click="openPrivacyPolicy">《隐私政策》</text>
            </text>
          </label>
        </checkbox-group>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isAgreed: false,
      showServiceAgreement: false,
      showPrivacyPolicy: false
    };
  },
  methods: {
    // 处理协议勾选
    handleAgreementChange(e) {
      this.isAgreed = e.detail.value.length > 0;
    },

    // 微信登录
   handleWechatLogin() {
     if (!this.isAgreed) {
       uni.showToast({ title: '请先同意用户协议和隐私政策', icon: 'none' });
       return;
     }
     // 直接在按钮点击回调中调用 wx.getUserProfile（用户主动触发）
     wx.getUserProfile({
       desc: '用于登录和完善个人信息', // 清晰的授权用途说明
       success: async (userRes) => {
         const { encryptedData, iv } = userRes;
         console.log(userRes)
		 
         // 获取登录凭证（必须在用户授权后调用，保持上下文）
         const loginResult = await new Promise((resolve, reject) => {
           wx.login({ success: resolve, fail: reject });
         });
         if (!loginResult.code) {
           uni.showToast({ title: '登录凭证获取失败', icon: 'none' });
           return;
         }
         const code = loginResult.code;
		 console.log(code)
		const avatar_url=userRes.userInfo.avatarUrl;
		const nickname=userRes.userInfo.nickName;
         // 调用后端接口
         try {
           const loginRes = await uni.request({
             url: 'http://localhost:9527/api/wx-login',
             method: 'POST',
             data: { code, encryptedData, iv ,avatar_url ,nickname},
             header: { 'content-type': 'application/json' }
           });
			console.log(loginRes)
           if (loginRes.statusCode !== 200 || loginRes.data.errcode) {
             throw new Error(loginRes.data.errmsg || '登录失败');
           }
     
           // 保存用户信息和 token
		   uni.setStorageSync('uid', loginRes.data.data.id);
           uni.setStorageSync('token', loginRes.data.data.token);
           uni.setStorageSync('userInfo', loginRes.data.data.userInfo);
     
           // 跳转到 tabBar 页面（确保目标页面在 pages.json 中配置了 tabBar）
           uni.switchTab({ url: '/pages/discover/index' });
         } catch (error) {
           console.error('登录接口调用失败:', error);
           uni.showToast({ title: '登录失败，请重试', icon: 'none' });
         }
       },
       fail: (err) => {
         console.error('用户授权失败:', err);
         if (err.errCode === 10004) { // 用户点击授权弹窗的“拒绝”按钮
           uni.showToast({ title: '请授权后再登录', icon: 'none' });
         }
       }
     });
   },

    // 跳转到验证码登录页面
    navigateToVerifyCodeLogin() {
      uni.navigateTo({
        url: '/pages/login/verify-code'
      });
    },

    // 打开服务协议
    openServiceAgreement() {
      uni.navigateTo({
        url: '/pages/agreement/service'
      });
    },

    // 打开隐私政策
    openPrivacyPolicy() {
      uni.navigateTo({
        url: '/pages/agreement/privacy'
      });
    }
  }
};
</script>

<style lang="scss">
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
}

.login-box {
  width: 100%;
  max-width: 750rpx;
  background: rgba(255, 255, 255, 0.98);
  border-radius: 40rpx;
  padding: 80rpx 60rpx;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
  transform: translateY(0);
  transition: transform 0.3s ease;
  margin: 0 auto;

  &:hover {
    transform: translateY(-5rpx);
  }
}

.logo-area {
  text-align: center;
  margin-bottom: 60rpx;

  .logo {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 30rpx;
    filter: drop-shadow(0 4rpx 8rpx rgba(0, 0, 0, 0.1));
  }

  .title {
    font-size: 48rpx;
    font-weight: 800;
    background: linear-gradient(45deg, #2c3e50, #3498db);
    -webkit-background-clip: text;
    color: transparent;
    letter-spacing: 4rpx;
    margin-bottom: 20rpx;
    display: block;
  }

  .slogan {
    font-size: 32rpx;
    color: #666;
    font-weight: 500;
    letter-spacing: 2rpx;
    font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
    background: linear-gradient(45deg, #34495e, #7f8c8d);
    -webkit-background-clip: text;
    color: transparent;
  }
}

.login-methods {
  margin-top: 80rpx;

  .login-btn {
    width: 100%;
    height: 100rpx;
    border-radius: 50rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 40rpx;
    font-size: 36rpx;
    font-weight: 600;
    border: none;
    transition: all 0.3s ease;
    box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.08);

    .iconfont {
      margin-right: 16rpx;
      font-size: 44rpx;
    }

    &.primary {
      background: linear-gradient(45deg, #2c3e50, #3498db);
      color: #ffffff;

      &:active {
        transform: scale(0.98);
        box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.08);
      }
    }

    &.wechat {
      background: linear-gradient(45deg, #07C160, #0a9d4e);
      color: #ffffff;

      &:active {
        transform: scale(0.98);
        box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.08);
      }
    }
  }
}

.other-login {
  margin-top: 60rpx;

  .divider {
    display: block;
    text-align: center;
    color: #666666;
    font-size: 30rpx;
    margin-bottom: 50rpx;
    position: relative;
    font-weight: 500;

    &::before,
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      width: 140rpx;
      height: 1px;
      background: linear-gradient(90deg, transparent, #666666, transparent);
    }

    &::before {
      left: 50%;
      margin-left: -200rpx;
    }

    &::after {
      right: 50%;
      margin-right: -200rpx;
    }
  }

  .login-options {
    display: flex;
    justify-content: center;
    gap: 100rpx;

    .option {
      display: flex;
      flex-direction: column;
      align-items: center;
      color: #444444;
      font-size: 30rpx;
      transition: all 0.3s ease;
      padding: 24rpx;
      border-radius: 24rpx;

      &:active {
        background: rgba(0, 0, 0, 0.05);
      }

      .iconfont {
        font-size: 64rpx;
        margin-bottom: 16rpx;
        color: #2c3e50;
        transition: transform 0.3s ease;
      }

      &:hover .iconfont {
        transform: scale(1.1);
      }
    }
  }
}

.agreement {
  margin-top: 80rpx;
  text-align: center;

  .agreement-label {
    display: inline-flex;
    align-items: center;
    font-size: 26rpx;
    color: #666666;
  }

  .agreement-text {
    margin-left: 10rpx;
  }

  .link {
    color: #3498db;
    text-decoration: none;
    font-weight: 500;
    position: relative;

    &::after {
      content: '';
      position: absolute;
      bottom: -2rpx;
      left: 0;
      width: 100%;
      height: 1px;
      background: #3498db;
      transform: scaleX(0);
      transition: transform 0.3s ease;
    }

    &:active::after {
      transform: scaleX(1);
    }
  }
}
</style>    