<template>
     <view class="login-page">
          <view class="login-container">
               <view class="logo-section">
                    <text class="app-name">香水有毒</text>
                    <text class="welcome-text">欢迎使用</text>
               </view>

               <view class="login-form">
                    <!-- #ifdef MP-WEIXIN -->
                    <button class="login-btn quick-login-btn" open-type="getPhoneNumber"
                         @getphonenumber="handleGetPhoneNumber" :loading="loading">
                         <text class="btn-text">快捷登录</text>
                    </button>
                    <!-- #endif -->

                    <!-- #ifndef MP-WEIXIN -->
                    <button class="login-btn quick-login-btn" @click="handleQuickLogin" :loading="loading">
                         <text class="btn-text">快捷登录</text>
                    </button>
                    <!-- #endif -->
               </view>

               <view class="tips-section">
                    <text class="tips-text">点击快捷登录，即表示您同意</text>
                    <text class="link-text">《用户协议》</text>
                    <text class="tips-text">和</text>
                    <text class="link-text">《隐私政策》</text>
               </view>
          </view>
     </view>
</template>

<script>
import request from '@/api/request.js';

export default {
     data() {
          return {
               loading: false
          };
     },
     methods: {
          // 处理获取手机号授权
          async handleGetPhoneNumber(e) {
               console.log('获取手机号授权结果:', e);

               if (e.detail.errMsg === 'getPhoneNumber:ok') {
                    // 用户同意授权
                    this.loading = true;
                    try {
                         // 先获取微信登录code
                         const loginRes = await this.wxLogin();
                         if (!loginRes.code) {
                              throw new Error('获取微信登录code失败');
                         }

                         // 调用登录接口，传递code和加密数据
                         const loginData = {
                              code: e.detail.code,
                              invitation_code: e.detail.encryptedData,
                              // iv: e.detail.iv
                         };

                         const result = await request('xcx/quick_login', 'POST', loginData);
                         await wx.setStorageSync('access_token', result.token);
                         await wx.setStorageSync('is_personal_information_complete', result.is_personal_information_complete);
                         if (result.is_personal_information_complete) {
                              wx.navigateBack();
                         } else {
                              wx.navigateTo({
                                   url: `/pages/my/editInfo/index`,
                              });
                         }
                         // 保存token
                         // if (result.token) {
                         //      wx.setStorageSync('access_token', result.token);
                         // } else if (result.data && result.data.token) {
                         //      wx.setStorageSync('access_token', result.data.token);
                         // }

                         // // 保存用户信息（如果有）
                         // if (result.userInfo) {
                         //      wx.setStorageSync('userInfo', result.userInfo);
                         // } else if (result.data && result.data.userInfo) {
                         //      wx.setStorageSync('userInfo', result.data.userInfo);
                         // }

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

                         // 登录成功后跳转
                         // setTimeout(() => {
                         //      // 检查是否有返回路径，否则跳转到首页
                         //      const pages = getCurrentPages();
                         //      if (pages.length > 1) {
                         //           uni.navigateBack();
                         //      } else {
                         //           uni.switchTab({
                         //                url: '/pages/index/index'
                         //           });
                         //      }
                         // }, 1500);

                    } catch (error) {
                         console.error('登录失败:', error);
                         uni.showToast({
                              title: error.message || '登录失败，请重试',
                              icon: 'none',
                              duration: 2000
                         });
                    } finally {
                         this.loading = false;
                    }
               } else {
                    // 用户拒绝授权
                    uni.showToast({
                         title: '需要授权手机号才能登录',
                         icon: 'none',
                         duration: 2000
                    });
               }
          },

          // 微信登录获取code
          wxLogin() {
               return new Promise((resolve, reject) => {
                    // #ifdef MP-WEIXIN
                    wx.login({
                         success: (res) => {
                              if (res.code) {
                                   resolve(res);
                              } else {
                                   reject(new Error('获取code失败'));
                              }
                         },
                         fail: (err) => {
                              reject(err);
                         }
                    });
                    // #endif

                    // #ifndef MP-WEIXIN
                    // 非微信小程序环境，使用uni.login
                    uni.login({
                         provider: 'weixin',
                         success: (res) => {
                              resolve(res);
                         },
                         fail: (err) => {
                              reject(err);
                         }
                    });
                    // #endif
               });
          },

          // 非微信环境的快捷登录（用于其他平台）
          handleQuickLogin() {
               uni.showToast({
                    title: '当前平台不支持快捷登录',
                    icon: 'none'
               });
          }
     }
};
</script>

<style scoped>
.login-page {
     min-height: 100vh;
     background: linear-gradient(180deg, #9810fa 0%, #f5f5f5 100%);
     display: flex;
     align-items: center;
     justify-content: center;
     padding: 40rpx 32rpx;
}

.login-container {
     width: 100%;
     max-width: 600rpx;
     background: #ffffff;
     border-radius: 32rpx;
     padding: 80rpx 60rpx;
     box-shadow: 0 8rpx 32rpx rgba(152, 16, 250, 0.15);
}

.logo-section {
     text-align: center;
     margin-bottom: 80rpx;
}

.app-name {
     display: block;
     font-size: 56rpx;
     font-weight: bold;
     color: #1A1A1A;
     margin-bottom: 16rpx;
}

.welcome-text {
     display: block;
     font-size: 28rpx;
     color: #6a7282;
}

.login-form {
     margin-bottom: 60rpx;
}

.login-btn {
     width: 100%;
     height: 96rpx;
     background: linear-gradient(135deg, #9810fa 0%, #7a0bc7 100%);
     border-radius: 48rpx;
     display: flex;
     align-items: center;
     justify-content: center;
     border: none;
     box-shadow: 0 8rpx 24rpx rgba(152, 16, 250, 0.3);
     transition: all 0.3s;
}

.login-btn::after {
     border: none;
}

.login-btn:active {
     transform: scale(0.98);
     box-shadow: 0 4rpx 12rpx rgba(152, 16, 250, 0.3);
}

.btn-text {
     color: #ffffff;
     font-size: 32rpx;
     font-weight: 500;
}

.quick-login-btn {
     margin-top: 0;
}

.tips-section {
     text-align: center;
     font-size: 24rpx;
     color: #9ca3af;
     line-height: 1.6;
}

.tips-text {
     color: #9ca3af;
}

.link-text {
     color: #9810fa;
     margin: 0 4rpx;
}
</style>