<template>
  <view class="login-container">
    <image class="login-image" src="https://data.qicai321.com/minlong/8baae825-6aa1-4783-9875-44d699f297cb.jpg" mode="aspectFit"></image>
    <view class="login-title">奇才，只选对的</view>
    <button class="login-btn" @click="handleLogin">微信登录</button>
    <view class="agreement">
      <checkbox :checked="isAgreed" @tap="toggleAgreement" color="#0039b3" />
      <text class="agreement-text">
        我已阅读并同意
        <text class="agreement-link" @tap="navigateToAgreement">《用户协议》</text>
       <!--  和
        <text class="agreement-link" @tap="navigateToPrivacy">《隐私政策》</text> -->
      </text>
    </view>
  </view>
</template>

<script>
import { wxLogin,getUserInfo } from '@/api/user';

export default {
  data() {
    return {
      isAgreed: false,
      wxLoginCode: ''
    }
  },
  methods: {
    toggleAgreement() {
      this.isAgreed = !this.isAgreed;
    },
    handleLogin() {
      if (!this.isAgreed) {
        uni.showToast({
          title: '请先阅读并同意相关协议',
          icon: 'none'
        });
        return;
      }
      
      // 添加确认对话框
      uni.showModal({
        title: '微信登录',
        content: '是否使用微信账号登录？',
        confirmText: '确认登录',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 用户点击确认，继续登录流程
            this.getWxLoginCode();
          } else {
            // 用户点击取消，不执行登录
            console.log('用户取消了登录');
            uni.showToast({
              title: '已取消登录',
              icon: 'none'
            });
          }
        }
      });
    },
    
    getWxLoginCode() {
      uni.showLoading({ title: '登录中...' });
      
      uni.login({
        provider: 'weixin',
        success: (loginRes) => {
          console.log('获取微信登录code成功:', loginRes.code);
          this.wxLoginCode = loginRes.code;
          uni.hideLoading();
          this.getUserProfile();
        },
        fail: (err) => {
          uni.hideLoading();
          console.error('获取微信登录code失败:', err);
          uni.showToast({
            title: '微信登录失败',
            icon: 'none'
          });
        }
      });
    },
    
    getUserProfile() {
      wx.getUserProfile({
        desc: '用于完善用户资料',
        success: (profileRes) => {
          console.log('获取用户信息成功:', profileRes);
          
          const loginParams = {
            code: this.wxLoginCode,
            userInfo: profileRes.userInfo,
            tenant_id: 1,
            signature: profileRes.signature,
            rawData: profileRes.rawData,
            encryptedData: profileRes.encryptedData,
            iv: profileRes.iv
          };
          
          this.wxLoginRequest(loginParams);
        },
        fail: (err) => {
          console.error('获取用户信息失败:', err);
          
          this.wxLoginRequest({ 
            code: this.wxLoginCode,
            userInfo: {
              nickName: '微信用户',
              avatarUrl: '',
              gender: 0,
              province: '',
              city: '',
              country: '',
              tenant_id: 1
            },
            tenant_id: 1
            
          });
        }
      });
    },
    
    async wxLoginRequest(loginParams) {
      try {
        uni.showLoading({ title: '登录中...' });
        
        console.log('发送登录请求，参数:', loginParams);
        
        const data = await wxLogin(loginParams);
        console.log('登录成功，返回数据:', data);
        
        const userData = this.buildUserData(data, loginParams);
        
        this.saveLoginState(data, userData);
      } catch (error) {
        this.handleLoginError(error, loginParams);
      }
    },
    
    buildUserData(data, loginParams) {
      console.log('构建用户数据，服务器返回:', data);
      
      let userData = {
        username: data.username || data.nickName || 
                (loginParams.userInfo ? loginParams.userInfo.nickName : '微信用户'),
        
        name: data.name || data.username || data.nickName || 
             (loginParams.userInfo ? loginParams.userInfo.nickName : ''),
        
        id: data.id || data.userId || data.user_id || data.openid || '',
        
        userId: data.userId || data.user_id || data.id || data.openid || '',
        
        avatar: data.avatar || data.avatarUrl || 
              (loginParams.userInfo ? loginParams.userInfo.avatarUrl : '/static/avatar.png'),
        
        phone: data.phone || data.mobile || '',
        gender: data.gender || (loginParams.userInfo ? loginParams.userInfo.gender : 0),
        
        openid: data.openid || '',
        unionid: data.unionid || '',
        session_key: data.session_key || '',
        
        is_new_user: data.is_new_user || false,
        
        loginTime: new Date().getTime(),
        /* tenant_id: 1 */
      };
      
      console.log('构建的用户数据:', userData);
      return userData;
    },
    
    saveLoginState(data, userData) {
      const token = data.token || data.session_key || '';
      if (token) {
        uni.setStorageSync('token', token);
        console.log('Token已保存:', token);
      }
      
      if (userData.avatar) {
        console.log('用户头像已保存:', userData.avatar);
      } else if (data.avatarUrl) {
        userData.avatar = data.avatarUrl;
      }
      
      // 先保存基本用户信息，确保有登录状态
      uni.setStorageSync('userInfo', JSON.stringify(userData));
      console.log('基本用户信息已保存');
      
      // 如果有用户ID，则获取完整的用户信息
      if (userData.id) {
        this.fetchUserDetail(userData.id, userData,userData.openid);
      } else {
        // 如果没有用户ID，直接完成登录流程
        this.completeLogin();
      }
    },
    
    // 获取用户详细信息
    async fetchUserDetail(userId, basicUserData, openid) {
      try {
        console.log('获取用户详细信息，用户ID:', userId);
        
        // 调用获取用户详情API
        const userDetail = await getUserInfo(userId, openid);
        console.log('获取用户详细信息成功:', userDetail);
        
        if (userDetail) {
          // 合并基本信息和详细信息
          const updatedUserInfo = {
            ...basicUserData,
            // 更新基本信息
            name: userDetail.name || basicUserData.name,
            phone: userDetail.phone || userDetail.mobile || basicUserData.phone,
            gender: userDetail.gender || basicUserData.gender,
            
            // 添加详细信息
            id_card: userDetail.id_card || '',
            emergency_contact: userDetail.emergency_contact || '',
            emergency_phone: userDetail.emergency_phone || '',
            relation: userDetail.relation || '',
            
            // 其他可能的字段
            ...userDetail
          };
          
          // 更新本地存储
          uni.setStorageSync('userInfo', JSON.stringify(updatedUserInfo));
          console.log('用户详细信息已更新并保存');
        }
      } catch (error) {
        console.error('获取用户详细信息失败:', error);
        // 获取详细信息失败不影响登录流程
      } finally {
        // 无论成功失败都完成登录流程
        this.completeLogin();
      }
    },
    
    // 完成登录流程
    completeLogin() {
      uni.hideLoading();
      uni.showToast({
        title: '登录成功',
        icon: 'success',
        success: () => {
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/index/index'
            });
			// uni.navigateTo({
			// 	url:'/pages/Personal/Personal'
			// })
          }, 1500);
        }
      });
    },
    
    handleLoginError(error, loginParams) {
      uni.hideLoading();
      
      if (error.message && (
          error.message.includes('code无效') || 
          error.message.includes('已过期') || 
          error.message.includes('已被使用') ||
          error.status === 999)) {
        console.error('微信登录code无效，重新获取:', error);
        uni.showToast({
          title: 'code已过期，请重试',
          icon: 'none',
          duration: 2000
        });
        
        setTimeout(() => {
          this.getWxLoginCode();
        }, 1000);
        return;
      }
      
      console.error('微信登录失败:', error);
      uni.showToast({
        title: error.message || '登录失败',
        icon: 'none'
      });
    },
    
    navigateToPrivacy() {
      uni.navigateTo({
        url: '/pages/privacy/privacy'
      });
    },
    
    navigateToAgreement() {
      uni.navigateTo({
        url: '/pages/agreement/agreement'
      });
    }
  }
}
</script>

<style>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
  height: 100vh;
  background-color: #FFF;
}

.login-image {
  width: 90%;

  margin-bottom: 40rpx;
}

.login-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 200rpx;
  color: #333;
}

.login-btn {
  width: 80%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #0033cc;
  color: #fff;
  border-radius: 45rpx;
  font-size: 32rpx;
  margin-bottom: 30rpx;
}

.agreement {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
}

.agreement-text {
  font-size: 24rpx;
  color: #666;
  margin-left: 10rpx;
}

.agreement-link {
  color: #0039b3;
}
</style> 