<template>
  <view class="login-container">
    <!-- 登录标题 -->
    <text class="title">智能医疗问诊系统</text>

    <!-- 账号输入框 -->
    <input class="input-box" v-model="account" placeholder="请输入账号" />
    <!-- 密码输入框 -->
    <input class="input-box" v-model="password" type="password" password placeholder="请输入密码" />

    <!-- 登录和注册按钮 -->
    <view class="btn-group">
      <button class="login-btn" @tap="handleLogin">登录</button>
      <button class="register-btn" @tap="handleRegister">注册</button>
    </view>

    <!-- 微信登录按钮 -->
    <button 
      class="wechat-btn" 
      open-type="getPhoneNumber" 
      @getphonenumber="handleGetPhoneNumber"
      @tap="handleGetUserProfile"
    >
      <text class="btn-text">微信一键登录</text>
    </button>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-mask">
      <uni-spinner type="circular" color="#07c160" size="40"></uni-spinner>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      userInfo: null,
      rawData: null,
      account: 'patient',
      password: '123456'
    };
  },
  mounted() {
    this.initWechat();
  },
  methods: {
    initWechat() {
      // 移除依赖 WeixinJSBridge 的代码，因为小程序环境没有该对象
      console.log('跳过依赖 WeixinJSBridge 的初始化');
    },
    handleGetUserProfile() {
      uni.showLoading({
        title: '获取信息中...',
        mask: true
      });
      uni.getUserProfile({
        desc: '用于完善会员资料',
        success: (res) => {
          this.userInfo = res.userInfo;
          this.rawData = res.rawData;
          console.log('获取到的 rawData:', this.rawData); 
          uni.hideLoading();
        },
        fail: (err) => {
          console.error('获取用户信息失败:', err);
          // 针对不同错误类型给出不同提示
          if (err.errMsg.includes('getUserAvatarInfo fail')) {
            uni.showToast({ 
              title: '获取用户头像信息失败，请检查网络或更新微信版本', 
              icon: 'none' 
            });
          } else {
            uni.showToast({ 
              title: '请授权后再登录', 
              icon: 'none' 
            });
          }
          uni.hideLoading();
        }
      });
    },
    // 处理获取手机号事件
    handleGetPhoneNumber: async function(e) {
      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        if (!this.rawData) {
          console.error('请先授权获取用户信息');
          uni.showToast({ title: '请先授权获取用户信息', icon: 'none' });
          return;
        }
        try {
          uni.showLoading({
            title: '登录中...',
            mask: true
          });
          this.loading = true;
          const encryptedData = e.detail.encryptedData;
          const iv = e.detail.iv;
          
          const { code } = await new Promise((resolve, reject) => {
            uni.login({
              success: (res) => resolve(res),
              fail: (err) => reject(err)
            });
          });

          const response = await new Promise((resolve, reject) => {
            uni.request({
              url: 'http://localhost:8080/api/auth/wechat/login',
              method: 'POST',
              data: {
                code,
                encryptedData,
                iv,
                rawData: this.rawData
              },
              success: (res) => resolve(res),
              fail: (err) => {
                console.error('网络请求失败:', err);
                reject(err);
              }
            });
          });

          console.log('后端返回的完整数据:', response.data);

          if (response.data) {
            if (response.data.wxNickname && response.data.wxAvatarUrl) {
              wx.setStorageSync('userToken', response.data.token);
              wx.setStorageSync('userInfo', {
                userId: response.data.userId,
                wxNickname: response.data.wxNickname,
                wxAvatarUrl: response.data.wxAvatarUrl
              });
              // 跳转逻辑
              wx.switchTab({
                url: '/pages/home/index'
              });
            } else {
              console.error('后端未返回微信昵称或头像信息:', response.data);
              wx.showToast({ title: '获取用户信息失败，请重试', icon: 'none' });
            }
          } else {
            console.error('登录响应数据为空:', response);
            wx.showToast({ title: '登录失败，请重试', icon: 'none' });
          }
        } catch (error) {
          console.error('登录过程出错:', error);
          wx.showToast({ title: '登录失败，请重试', icon: 'none' });
        } finally {
          this.loading = false;
          wx.hideLoading();
        }
      } else {
        // 优化错误提示
        if (e.detail.errMsg.includes('getPhoneNumber:fail')) {
          wx.showToast({ 
            title: '获取手机号失败，请重试或检查授权', 
            icon: 'none' 
          });
        } else {
          console.error('用户拒绝授权', e.detail.errMsg);
          wx.showToast({ title: '请授权后再登录', icon: 'none' });
        }
      }
    },
    // 登录点击方法
    handleLogin() {
      uni.request({
        url: 'http://localhost:8080/user/login',
        method: 'POST',
        data: {
          username: this.account,
          password: this.password
        },
        success: (res) => {
          console.log('登录响应:', res.data);
          if (res.data.code == 200) {
            uni.showToast({
              title: '登录成功',
              icon: 'success'
            });
            // 清空输入框数据
            this.account = '';
            this.password = '';
            uni.switchTab({
              url: '/pages/home/index'
            });
          } else {
            uni.showToast({
              title: res.data.message || '登录失败，请重试',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('登录请求失败:', err);
          uni.showToast({
            title: '网络错误，请重试',
            icon: 'none'
          });
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    },
    // 注册点击方法
    handleRegister() {
      uni.request({
        url: 'http://localhost:8080/user/register',
        method: 'POST',
        data: {
          username: this.account,
          password: this.password
        },
        success: (res) => {
          console.log('注册响应:', res.data);
          if (res.data.code == 200) {
            uni.showToast({
              title: '注册成功',
              icon: 'success'
            });
            // 清空输入框数据
            this.account = '';
            this.password = '';
            // 可以在这里添加注册成功后的逻辑，如跳转到登录页
          } else {
            uni.showToast({
              title: res.data.message || '注册失败，请重试',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('注册请求失败:', err);
          uni.showToast({
            title: '网络错误，请重试',
            icon: 'none'
          });
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.title {
  font-size: 36rpx;
  color: #1a73e8;
  margin-bottom: 80rpx;
  font-weight: bold;
}

.input-box {
  width: 600rpx;
  height: 120rpx;
  margin-bottom: 40rpx;
  padding: 0 20rpx;
  border: 2rpx solid #d9d9d9;
  border-radius: 12rpx;
  font-size: 32rpx;
  background-color: white;
}

.login-btn, .register-btn, .wechat-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 280rpx;
  height: 120rpx;
  color: white;
  border-radius: 60rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.15);
  font-size: 32rpx;
}

.login-btn {
  background-color: #1a73e8;
}

.register-btn {
  background-color: #ff9500;
}

.wechat-btn {
  background-color: #07c160;
  margin-top: 40rpx;
}

.wechat-btn .wechat-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 20rpx;
}

.btn-group {
  display: flex;
  justify-content: space-between;
  width: 600rpx;
}

.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}
</style>