<template>
  <view class="user-info-page">

    <view class="user-info-section">
      <!-- 点击获取头像 -->
      <button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" class="avatar-btn">
        <image v-if="avatarUrl" :src="avatarUrl" class="avatar-img"></image>
        <image v-else src="@/static/images/avatar.png" class="avatar-img"></image>
        <text class="tip-text">点击更换头像</text>
      </button>
    </view>

    <!-- 昵称 -->
    <view class="form-item">
      <text class="label">昵称</text>
      <input 
        class="input" 
        type="nickname" 
        v-model="nickName" 
        placeholder="请输入昵称"
      />
      <uni-icons type="right" size="18" color="#ccc"></uni-icons>
    </view>

    <!-- 保存按钮 -->
    <view class="save-box">
      <button class="save-btn" @click="saveUserInfo">保存修改</button>
    </view>
  </view>
</template>

<script>
import config from '@/utils/config'
import { FetchBindRead } from '@/api/user';

// 缓存 key 与个人中心保持一致
const USER_KEY = 'user-info';

export default {
  data() {
    return {
      nickName: '',
      avatarUrl: ''
    };
  },
  onLoad() {
    // 页面加载时获取本地缓存的用户信息
    this.loadUserInfo();
  },
  methods: {
    // 加载缓存中的用户信息
    loadUserInfo() {
      const userInfo = uni.getStorageSync(USER_KEY) || {};
      this.nickName = userInfo.nickName || '';
      this.avatarUrl = userInfo.avatarUrl || '';
    },

    // 选择微信头像
    async onChooseAvatar(e) {
      const tempFilePath = e.detail.avatarUrl;
      uni.showLoading({ title: '上传中...' });

      try {
        // 1. 上传头像到服务器
        const uploadRes = await new Promise((resolve, reject) => {
          uni.uploadFile({
            url: config.baseUrl + '/api/fileRelevant/uploadWxAvatarImg',
            filePath: tempFilePath,
            name: 'file',
            success: resolve,
            fail: reject
          })
        });

        const resData = JSON.parse(uploadRes.data);
        const imgId = resData.data;

        if (!imgId) {
          uni.showToast({ title: '头像上传失败', icon: 'none' });
          return;
        }

        // 拼接头像地址
        const avatarUrl = config.baseUrl + '/api/fileRelevant/getImg?imgType=5&imgId=' + imgId;
        this.avatarUrl = avatarUrl;

        uni.showToast({ title: '头像选择成功，点击保存生效', icon: 'success' });

      } catch (err) {
        console.error('头像上传失败：', err);
        uni.showToast({ title: '头像更新失败', icon: 'none' });
      } finally {
        uni.hideLoading();
      }
    },

    // 保存用户信息（头像 + 昵称）
    async saveUserInfo() {
      // 校验昵称
      if (!this.nickName.trim()) {
        uni.showToast({ title: '请输入昵称', icon: 'none' });
        return;
      }

      uni.showLoading({ title: '保存中...' });

      try {
        const openId = uni.getStorageSync('wx_login_code') || '';
        const params = {
          avatar: this.avatarUrl,
          libcode: "1201",
          nickname: this.nickName,
          openid: openId
        };

        // 调用保存接口
        await FetchBindRead(params);

        // 更新缓存
        const userInfo = {
          nickName: this.nickName,
          avatarUrl: this.avatarUrl
        };
        uni.setStorageSync(USER_KEY, userInfo);

        uni.showToast({
          title: '保存成功',
          icon: 'success'
        });

        // 返回上一页
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);

      } catch (error) {
        console.error('保存失败：', error);
        uni.showToast({
          title: '保存失败，请重试',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.user-info-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20rpx;
  box-sizing: border-box;
}

/* 头像区域 */
.user-info-section {
  background: #fff;
  padding: 40rpx 0;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-btn {
  background: transparent;
  display: flex;
  flex-direction: column;
  align-items: center;
  
  &::after {
    border: none;
  }
}

.avatar-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 10rpx;
}

.tip-text {
  font-size: 26rpx;
  color: #999;
}

/* 表单项 */
.form-item {
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  height: 88rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.label {
  font-size: 30rpx;
  color: #333;
  width: 120rpx;
}

.input {
  flex: 1;
  font-size: 30rpx;
  color: #333;
  text-align: right;
}

/* 保存按钮 */
.save-box {
  margin-top: 60rpx;
  padding: 0 20rpx;
}

.save-btn {
  height: 88rpx;
  line-height: 88rpx;
  background-color: #007aff;
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
}
</style>