<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '%myProfile.title%',
    navigationBarBackgroundColor: '#fff',
  },
}
</route>

<script lang="ts" setup>
import { updateInfo } from '@/api/login'
import { t } from '@/locale'
import { useUserStore } from '@/store'
import { getEnvBaseUploadUrl } from '@/utils'
import { toast } from '@/utils/toast'

defineOptions({
  name: 'MyProfile', // 我的资料
})

const userStore = useUserStore()
const userInfo = computed(() => {
  return getUserInfoHook()
})

const uploading = ref(false)

// 更新头像
async function updateAvatar() {
  try {
    // 使用 uni.chooseMedia 选择图片
    const res: any = await new Promise((resolve, reject) => {
      uni.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        success: resolve,
        fail: reject,
      })
    })

    if (!res.tempFiles || res.tempFiles.length === 0) {
      return
    }

    const tempFile = res.tempFiles[0]
    const tempFilePath = tempFile.tempFilePath

    // 检查文件大小（限制为5MB）
    const maxSize = 5 * 1024 * 1024
    if (tempFile.size > maxSize) {
      toast.error(t('myProfile.upload.sizeLimit'))
      return
    }

    uploading.value = true
    await uni.showLoading({
      title: t('myProfile.upload.uploading'),
      mask: true,
    })

    // 上传图片
    const uploadRes: any = await new Promise((resolve, reject) => {
      uni.uploadFile({
        url: `${getEnvBaseUploadUrl()}`,
        filePath: tempFilePath,
        name: 'file',
        success: resolve,
        fail: reject,
      })
    })
    console.log('uploadRes', uploadRes)
    // 解析上传结果
    const uploadData = JSON.parse(uploadRes.data)
    if (uploadData.code !== '200') {
      throw new Error(uploadData.message)
    }

    const avatarUrl = uploadData.data.url
    // 调用更新用户信息接口
    await updateInfo({
      headPic: avatarUrl,
    })
    // 更新本地用户信息
    const newUserInfo = { ...userInfo.value, headPic: avatarUrl }
    userStore.setUserInfo(newUserInfo)

    uni.hideLoading()
    toast.success(t('myProfile.upload.success'))
  }
  catch (error: any) {
    uni.hideLoading()
    console.error('Update avatar failed:', error)
    toast.error(error.message || t('myProfile.upload.error'))
  }
  finally {
    uploading.value = false
  }
}
</script>

<template>
  <z-paging>
    <view class="py-20rpx">
      <wd-cell-group custom-class="mb-20rpx" border>
        <wd-cell :title="t('myProfile.avatar')" center>
          <view class="flex items-center justify-end" @click="updateAvatar">
            <view class="relative flex items-center justify-center">
              <wd-img width="64rpx" height="64rpx" round :src="userInfo.headPic" />
              <view v-if="uploading" class="absolute inset-0 flex items-center justify-center rounded-full bg-black bg-opacity-50">
                <wd-loading size="20rpx" color="#fff" />
              </view>
            </view>
            <wd-icon name="arrow-right" custom-class="ml-10rpx" size="36rpx" />
          </view>
        </wd-cell>
        <wd-cell :title="$t('myProfile.userId')" :value="userInfo.userId" />
        <wd-cell :title="$t('myProfile.userName')" :value="userInfo.name" />
        <wd-cell :title="$t('myProfile.mobileNumber')" :value="userInfo.phoneNo" />
      </wd-cell-group>
      <wd-cell-group custom-class="mb-20rpx" border>
        <wd-cell :title="$t('myProfile.bankName')" :value="userInfo.bank" />
        <wd-cell :title="$t('myProfile.bankAccountName')" :value="userInfo.bankAccountName" />
        <wd-cell :title="$t('myProfile.bankAccountNo')" :value="userInfo.bankAccount" />
      </wd-cell-group>
    </view>
  </z-paging>
</template>

<style lang="scss" scoped>
//
</style>
