<template>
  <view class="user-info-container">
        
    <!-- 内容区域 -->
    <view class="content">
      <!-- 头像区域 -->
      <view class="avatar-section">
        <view class="app-info">
          <image 
            class="app-logo" 
            :src="configParamImage('config_logo')" 
            mode="aspectFit"
          ></image>
          <text class="app-name">{{ configParamText('config_app_name') }}</text>
        </view>
      </view>
      
      <!-- 表单区域 -->
      <view class="form-section">
        <!-- 头像 -->
        <!-- 在模板中修改头像区域 -->
        <view class="form-item">
          <text class="form-label">头像</text>
          <view class="avatar-upload">
            <button 
              class="avatar-button" 
              open-type="chooseAvatar" 
              @chooseavatar="onChooseAvatar"
            >
              <image 
                class="avatar-image" 
                :src="userInfo.headImage || '/static/upload-avatar.png'" 
                mode="aspectFill"
              ></image>
            </button>
          </view>
        </view>
        
        <!-- 昵称 -->
        <view class="form-item">
          <text class="form-label">昵称</text>
          <input 
            class="form-input" 
            v-model="userInfo.nickName" 
            placeholder="请输入昵称"
            type="nickname"
            @blur="onNicknameBlur"
          />
        </view>
        
        <!-- 手机号 -->
        <view class="form-item">
          <text class="form-label">手机号</text>
          <view class="phone-input-container">
            <input 
              class="form-input phone-input" 
              v-model="userInfo.phone" 
              placeholder="请输入手机号"
              type="number"
              maxlength="11"
            />
            <button 
              class="get-phone-btn" 
              open-type="getPhoneNumber" 
              @getphonenumber="getPhoneNumber"
            >
              <text class="btn-text">获取手机号</text>
            </button>
          </view>
        </view>
      </view>
      
      <!-- 确定按钮 -->
      <view class="submit-section">
        <view class="submit-btn" @click="submitUserInfo">
          <text class="submit-text">确定</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'UserInfo',
  data() {
    return {
      userInfo: {
        headImage: '',
        nickName: '',
        phone: ''
      }
    }
  },
  onLoad() {
    // 获取微信用户信息
    this.getWechatUserInfo();
  },
  methods: {
    // 获取微信用户信息
    async getWechatUserInfo() {
     const { result } = await this.$api.user.queryUser()
      this.userInfo.nickName = result.nickName
      this.userInfo.headImage = result.headImage
      this.userInfo.phone = result.phone
    },
    
    // 提交表单
    // 选择头像并上传到OSS
    async onChooseAvatar(e) {
      console.log('选择头像回调', e);
      if (e.detail.avatarUrl) {
        try {
          // 显示上传中提示
          uni.showLoading({ title: '上传头像中...' });
          
          // 构造文件对象
          const file = {
            path: e.detail.avatarUrl,
            tempFilePath: e.detail.avatarUrl
          };
          
          // 上传到OSS
          const uploadResult = await this.$utils.uploadImage(file);
          
          uni.hideLoading();
          
          if (uploadResult.success) {
            // 上传成功，更新头像URL
            this.userInfo.headImage = uploadResult.url;
            console.log('头像上传成功', uploadResult.url);
            uni.showToast({
              title: '头像上传成功',
              icon: 'success'
            });
          } else {
            // 上传失败，使用本地头像
            // this.userInfo.headImage = e.detail.avatarUrl;
            uni.showToast({
              title: '头像上传失败！请稍后重试！',
              icon: 'none'
            });
          }
        } catch (error) {
          uni.hideLoading();
          console.error('头像上传异常:', error);
          // 异常情况下使用本地头像
          this.userInfo.headImage = e.detail.avatarUrl;
          uni.showToast({
            title: '头像处理异常，使用本地头像',
            icon: 'none'
          });
        }
      } else {
        uni.showToast({
          title: '头像选择失败',
          icon: 'none'
        });
      }
    },
    

    // 昵称输入失焦
    onNicknameBlur() {
      if (!this.userInfo.nickname.trim()) {
        uni.showToast({
          title: '请输入昵称',
          icon: 'none'
        });
      }
    },
    
    // 获取手机号
    async getPhoneNumber(e) {
      console.log('获取手机号回调', e);
      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        // 获取成功，可以通过e.detail.code发送到后端换取手机号
        console.log('获取手机号成功', e.detail);
        const res = await this.$api.login.bindPhone({
          phoneCode: e.detail.code
        })
        const str = JSON.parse(res.result);
        this.userInfo.phone = str.phone_info.phoneNumber
        uni.showToast({
          title: '手机号获取成功',
          icon: 'success'
        });
        // 这里需要将e.detail.code发送到后端解密获取真实手机号
        // 暂时模拟设置手机号
        // this.userInfo.phone = '138****8888';
      } else {
        // 如果失败了就申请开启权限
        uni.showToast({
          title: '手机号获取失败',
          icon: 'error'
        })
      }
    },
    
    // 提交用户信息
    async submitUserInfo() {
      if (!this.userInfo.nickName.trim()) {
        uni.showToast({
          title: '请输入昵称',
          icon: 'none'
        });
        return;
      }
      
      if (!this.userInfo.phone.trim()) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        });
        return;
      }
      
      if (!/^1[3-9]\d{9}$/.test(this.userInfo.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        });
        return;
      }
      
      console.log('提交用户信息', this.userInfo);
      
      // 提交用户信息
      await this.$api.user.updateUser({
        nickName: this.userInfo.nickName,
        phone: this.userInfo.phone,
        headImage: this.userInfo.headImage,
        address: ''
      })

      // 这里可以调用API保存用户信息
      uni.showToast({
        title: '信息保存成功',
        icon: 'success'
      });
      
      // 跳转到首页或其他页面
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/index/index'
        });
      }, 1000);
    }
  }
}
</script>

<style lang="scss" scoped>
.user-info-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background-color: #1488DB;
  
  .navbar-content {
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: var(--status-bar-height, 44rpx);
    
    .navbar-title {
      font-size: 36rpx;
      font-weight: 500;
      color: #ffffff;
    }
  }
}

.content {
  padding-top: calc(88rpx + var(--status-bar-height, 44rpx));
  padding: calc(88rpx + var(--status-bar-height, 44rpx)) 40rpx 40rpx;
}

.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 80rpx;
  
  .app-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .app-logo {
      width: 160rpx;
      height: 160rpx;
      border-radius: 20rpx;
      border: 4rpx dashed #cccccc;
      margin-bottom: 20rpx;
    }
    
    .app-name {
      font-size: 32rpx;
      font-weight: 500;
      color: #333333;
    }
  }
}

.form-section {
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 60rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .form-label {
    width: 120rpx;
    font-size: 32rpx;
    color: #333333;
    font-weight: 500;
  }
  
  .form-input {
    flex: 3;
    height: 80rpx;
    padding: 0 20rpx;
    // border: 2rpx solid #e0e0e0;
    border-radius: 10rpx;
    font-size: 30rpx;
    color: #333333;
    
    &.phone-input {
      margin-right: 20rpx;
    }
  }
  
  .avatar-upload {
    .avatar-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 10rpx;
      border: 2rpx dashed #cccccc;
    }
  }
  
  .phone-input-container {
    flex: 1;
    display: flex;
    align-items: center;
    
    .get-phone-btn {
      flex: 2;
      // padding: 0rpx 0rpx;
      background-color: #1488DB;
      border-radius: 40rpx;
      border: none;
      outline: none;
      
      &::after {
        border: none;
      }
      
      .btn-text {
        font-size: 26rpx;
        color: #ffffff;
      }
    }
  }
}

.submit-section {
  padding: 0 40rpx;
  
  .submit-btn {
    width: 100%;
    height: 88rpx;
    background-color: #1488DB;
    border-radius: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .submit-text {
      font-size: 32rpx;
      font-weight: 500;
      color: #ffffff;
    }
  }
}
// 添加按钮样式
.avatar-button {
  padding: 0;
  margin: 0;
  background: transparent;
  border: none;
  outline: none;
  
  &::after {
    border: none;
  }
}
</style>