<template>
  <view class="page-container">
    <!-- 顶部导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-back" @click="handleBack">
        <text class="back-icon">←</text>
      </view>
      <view class="navbar-title">
        <text class="title-text">编辑资料</text>
      </view>
      <view class="navbar-placeholder"></view>
    </view>

    <scroll-view class="scroll-view" scroll-y>
      <view class="content-wrapper">
        <!-- 表单卡片 -->
        <view class="form-card">
          <!-- 头像 -->
          <view class="form-item">
            <text class="item-label">头像</text>
            <view class="avatar-section">
              <button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                <image class="avatar-preview" :src="avatarUrl" mode="aspectFill"></image>
              </button>
              <text class="change-tip">点击更换</text>
            </view>
          </view>

          <!-- 昵称 -->
          <view class="form-item">
            <text class="item-label">昵称</text>
            <input 
              class="item-input" 
              type="nickname" 
              v-model="nickname" 
              placeholder="请输入昵称"
              maxlength="20"
            />
          </view>

          <!-- 手机号（只读） -->
          <view class="form-item" v-if="phone">
            <text class="item-label">手机号</text>
            <text class="item-value">{{ formatPhone(phone) }}</text>
          </view>
        </view>

        <!-- 保存按钮 -->
        <view class="action-section">
          <button class="save-btn" @click="handleSave" :disabled="saving">
            {{ saving ? '保存中...' : '保存' }}
          </button>
        </view>

        <view class="bottom-safe-area"></view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { getUserInfo, setUserInfo, refreshUserInfo } from '@/utils/auth.js'
import { updateUserProfile } from '@/utils/api.js'

const avatarUrl = ref('/static/images/head.png')
const nickname = ref('')
const phone = ref('')
const originalAvatar = ref('')
const originalNickname = ref('')
const saving = ref(false)

const handleBack = () => {
  const pages = getCurrentPages()
  pages.length > 1 ? uni.navigateBack() : uni.switchTab({ url: '/pages/mine/mine' })
}

onMounted(() => {
  loadUserInfo()
})

onShow(() => {
  loadUserInfo()
})

const loadUserInfo = async () => {
  // 先显示本地缓存
  const userInfo = getUserInfo()
  if (userInfo) {
    avatarUrl.value = userInfo.avatar || '/static/images/head.png'
    nickname.value = userInfo.nickname || ''
    phone.value = userInfo.phone || ''
    originalAvatar.value = avatarUrl.value
    originalNickname.value = nickname.value
  }
  
  // 刷新最新状态
  const latestInfo = await refreshUserInfo()
  if (latestInfo) {
    avatarUrl.value = latestInfo.avatar || '/static/images/head.png'
    nickname.value = latestInfo.nickname || ''
    phone.value = latestInfo.phone || ''
    originalAvatar.value = avatarUrl.value
    originalNickname.value = nickname.value
  }
}

const formatPhone = (p) => {
  if (!p || p.length !== 11) return p
  return p.substring(0, 3) + '****' + p.substring(7)
}

const onChooseAvatar = (e) => {
  avatarUrl.value = e.detail.avatarUrl
}

const uploadAvatar = async (tempPath) => {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('user_token')
    uni.uploadFile({
      url: 'http://localhost:8081/v1/file/upload',
      filePath: tempPath,
      name: 'file',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const data = JSON.parse(res.data)
          if (data.code === 200 && data.data?.url) {
            resolve(data.data.url)
          } else {
            reject(new Error(data.message || '上传失败'))
          }
        } else {
          reject(new Error('上传失败'))
        }
      },
      fail: (err) => {
        reject(new Error('网络错误'))
      }
    })
  })
}

const handleSave = async () => {
  if (!nickname.value || nickname.value.trim() === '') {
    uni.showToast({ title: '请输入昵称', icon: 'none' })
    return
  }

  if (avatarUrl.value === originalAvatar.value && nickname.value === originalNickname.value) {
    uni.showToast({ title: '没有修改', icon: 'none' })
    return
  }

  saving.value = true
  uni.showLoading({ title: '保存中...' })

  try {
    let uploadedAvatarUrl = avatarUrl.value

    // 如果头像是临时文件路径，需要上传到OSS
    if (avatarUrl.value !== originalAvatar.value && 
        !avatarUrl.value.startsWith('/static/') && 
        !avatarUrl.value.startsWith('http')) {
      try {
        uploadedAvatarUrl = await uploadAvatar(avatarUrl.value)
      } catch (e) {
        console.warn('头像上传失败，使用默认头像:', e.message)
        uploadedAvatarUrl = '/static/images/head.png'
      }
    }

    // 调用后端接口更新用户信息
    await updateUserProfile({
      nickname: nickname.value.trim(),
      avatar: uploadedAvatarUrl
    })

    // 更新本地存储
    const userInfo = getUserInfo()
    userInfo.nickname = nickname.value.trim()
    userInfo.avatar = uploadedAvatarUrl
    setUserInfo(userInfo)

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

    setTimeout(() => {
      uni.navigateBack()
    }, 1500)

  } catch (error) {
    console.error('保存失败:', error)
    uni.hideLoading()
    uni.showToast({ title: error.message || '保存失败', icon: 'none' })
  } finally {
    saving.value = false
  }
}
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background: #f5f6fb;
  display: flex;
  flex-direction: column;
}

/* 导航栏 */
.custom-navbar {
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 80rpx 32rpx 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  position: relative;
}

.navbar-back {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
}

.back-icon {
  font-size: 40rpx;
  color: #222222;
  font-weight: bold;
}

.navbar-title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.title-text {
  font-size: 36rpx;
  font-weight: 600;
  color: #222222;
}

.navbar-placeholder {
  width: 80rpx;
}

/* 内容区 */
.scroll-view {
  flex: 1;
  height: 0;
}

.content-wrapper {
  padding: 32rpx;
}

/* 表单卡片 */
.form-card {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 16rpx 32rpx;
  box-shadow: 0 8rpx 24rpx rgba(37, 52, 94, 0.08);
  margin-bottom: 40rpx;
}

.form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 0;
  border-bottom: 1rpx solid #f5f6fb;
}

.form-item:last-child {
  border-bottom: none;
}

.item-label {
  font-size: 30rpx;
  font-weight: 600;
  color: #222222;
  min-width: 120rpx;
}

.avatar-section {
  display: flex;
  align-items: center;
}

.avatar-btn {
  background: transparent;
  border: none;
  padding: 0;
  margin: 0;
  line-height: normal;
}

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

.avatar-preview {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: #f5f6fb;
}

.change-tip {
  font-size: 26rpx;
  color: #5B5AEA;
  margin-left: 20rpx;
}

.item-input {
  flex: 1;
  height: 60rpx;
  font-size: 30rpx;
  color: #222222;
  text-align: right;
}

.item-value {
  font-size: 30rpx;
  color: #9ca2b5;
}

/* 保存按钮 */
.action-section {
  padding: 0 20rpx;
}

.save-btn {
  width: 100%;
  height: 96rpx;
  background: #5B5AEA;
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 600;
  border-radius: 48rpx;
  border: none;
  box-shadow: 0 12rpx 24rpx rgba(91, 90, 234, 0.3);
  line-height: 96rpx;
}

.save-btn:active {
  opacity: 0.9;
}

.save-btn[disabled] {
  opacity: 0.6;
}

.bottom-safe-area {
  height: 80rpx;
}
</style>
